1

我无法将此程序从 if-else-if 语句转换为 switch 语句。任何帮助,将不胜感激。

import java.util.Scanner;

public class ifToSwitchConversion {


    public static void main(String [] args) {

        // Declare a Scanner and a choice variable
        Scanner stdin = new Scanner(System.in);
        int choice = 0;

        System.out.println("Please enter your choice (1-4): ");
        choice = stdin.nextInt();

        if(choice == 1)
        {
            System.out.println("You selected 1.");
        }
        else if(choice == 2 || choice == 3)
        {
            System.out.println("You selected 2 or 3.");
        }
        else if(choice == 4)
        {
            System.out.println("You selected 4.");
        }
        else
        {
            System.out.println("Please enter a choice between 1-4.");
        }

    }


}
4

4 回答 4

4
import java.util.Scanner;

public class ifToSwitchConversion {

public static void main(String [] args) {

    // Declare a Scanner and a choice variable
    Scanner stdin = new Scanner(System.in);
    int choice = 0;

    System.out.println("Please enter your choice (1-4): ");
    choice = stdin.nextInt();


    switch(choice) {
        case 1:
            System.out.println("You selected 1.");
            break;
        case 2:
        case 3:
            System.out.println("You selected 2 or 3.");
            break;
        case 4:
            System.out.println("You selected 4.");
            break;
        default:
            System.out.println("Please enter a choice between 1-4.");
    }

  }

}
于 2013-09-27T00:18:39.980 回答
3

你可能想要这样的东西:

switch (choice) {
    case 1:
        System.out.println("You selected 1.");
        break;
    case 2:
    case 3:  // fall through
        System.out.println("You selected 2 or 3.");
        break;
    case 4:
        System.out.println("You selected 4.");
        break;
    default:
        System.out.println("Please enter a choice between 1-4.");
}

我敦促你阅读switch 语句教程,它应该解释它是如何/为什么这样工作的。

于 2013-09-27T00:11:29.753 回答
2
switch(choice)
{
    case 1:
        System.out.println("You selected 1.");
        break;
    case 2:
    case 3:
        System.out.println("You selected 2 or 3.");
        break;
    case 4:
        System.out.println("You selected 4.");
        break;
    default:
        System.out.println("Please enter a choice between 1-4.");
}
于 2013-09-27T00:11:27.820 回答
-2
/* Just change choice to 1
 * if you want 2 or 3 or 4
 * just change the switch(2 or 3 or 4) 
 */

switch(1)
{
    case 1:
        System.out.println("You selected 1.");
        break;
    case 2:
    case 3:
        System.out.println("You selected 2 or 3.");
        break;
    case 4:
        System.out.println("You selected 4.");
        break;
    default:
        System.out.println("Please enter a choice between 1-4.");
}

答案:您选择了 1。

于 2018-09-17T10:59:29.937 回答