将if-else-if语句转换为java中的switch语句

时间:2013-09-27 00:09:17

标签: java

我无法将此程序从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 个答案:

答案 0 :(得分: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.");
    }

  }

}

答案 1 :(得分: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 statement tutorial,这应该解释这是如何/为何如此有效。

答案 2 :(得分: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.");
}

答案 3 :(得分:-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。

相关问题