在交换机内部打印

问题描述 投票:0回答:2

期望的结果是打印“ i为零”,然后打印一,二,三,四..

似乎我的for循环工作正常,每次执行时i都变为5,但是我的情况都不是正确的,因此没有任何输出。我在做什么错?

public class SwitchTest {

    public static void main(String[] args) {
        int i;

        for ( i=0; i < 5; i++); {

        switch (i) {
            case 0:
                System.out.println("i is zero");
            case 1:
                System.out.println("i is one");
            case 2:
                System.out.println("i is two");
            case 3:
                System.out.println("i is three");
            case 4:
                System.out.println("i is four");
            }
        }
    }
}
java switch-statement
2个回答
0
投票

您需要在每个Sysout之后添加break语句。

switch (i) {
           case 0:
                System.out.println("i is zero");
                break;
            case 1:
                System.out.println("i is one");
                break;
            case 2:
                System.out.println("i is two");
                break;
            case 3:
                System.out.println("i is three");
                break;
            case 4:
                System.out.println("i is four");
                break;
            default:
               //some statement here.

     }

0
投票

没有输出任何内容,因为在您的for语句后加了分号,而Java也没有因为it's still valid syntax而抱怨。但是修复它,您会发现您的案例[[all在每次迭代中都会打印出来。这是因为,除非您用switch结束每个case语句,否则break语句将从相关案例一直执行到最底端。 switch (i) { case 0: System.out.println("i is zero"); break; //"break" means "exit the switch block here, don't go any further" case 1: System.out.println("i is one"); break; case 2: System.out.println("i is two"); break; case 3: System.out.println("i is three"); break; case 4: System.out.println("i is four"); break; //This one is optional }

为了获得良好的风格,您还应该包括一个default包,但这是另一回事了...]
© www.soinside.com 2019 - 2024. All rights reserved.