Switch Discrepancies的语法

时间:2015-11-04 23:47:27

标签: java switch-statement

根据java文档,switch语句示例如下所示:

public class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

我写了一个测试程序:

import java.util.Scanner;

public class Practice2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        switch (x)
        {
        case 1: x = 4;
            System.out.println("Hey");
            break;
        case 2: x = 5;
            System.out.println("You");
            break;
        default:
            System.out.println("as;ldfj'");
        }
    }
}

如果我选择1则选择案例1.如果我选择2则选择案例2.它实际上不会测试x = 4和x = 5.我使用Eclipse如果这有任何区别。我做错了什么?

1 个答案:

答案 0 :(得分:3)

x = 4在switch语句中不是一个例子,它是一个赋值。

如果您想要x == 4的案例,则在switch语句中需要case 4: