交换语句中的中断是否终止for循环?

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

我试图了解回报,打破和继续。我知道休息会停止(内部)for循环。例如:

for (int i = 1; i <= 3; i++) {
            // inner loop
            for (int j = 1; j <= 3; j++) {
                if (i == 2 && j == 2) {
                    // using break statement inside the inner loop
                    break;
                }
                System.out.println(i + " " + j);
            }
        }

我知道外部循环将继续。

我不明白的是这里:

for (int i = 0; i < 3; i++) {
            String line = null;
            switch (a) { 
                case 0:
                    line = "Hello";
                    break;
                case 1:
                    line = "How are you?";
                    break;
                case 2:
                    line = "What are you doing?";
                    break;

所以转到情况0,然后中断,for循环继续,为什么?我以为它不会嵌套,所以会打破循环。还是因为切换语句-与if语句不同?

在这种情况下,它将终止整个while循环...我看不到区别。

while(winner == false){

                input = menuInput.nextInt();

                try {
                    if(input == 0 || input >= 9){
                        System.out.println("Ungültige Nummer, versuche nochmal!");
                        break; 
                    }
java loops for-loop switch-statement break
2个回答
0
投票

您可以break一个switch。您不能breakifbreak应用于最可能被break处理的事物,因此

for (int j = 1; j <= 3; j++) {
    if (i == 2 && j == 2) {
        // using break statement inside the inner loop
         break;
    }
    System.out.println(i + " " + j);
}

这里break指的是for

在这里:

for (int i = 0; i < 3; i++) {
    String line = null;
    switch (a) { 
        case 0:
            line = "Hello";
            break;

switch

break可以是forwhiledo...whileswitch

有关更多信息,请参见the spec


0
投票

break适用于可以被打断的最里面的东西(无标签)。在这种情况下,它是switch-因为默认的switch行为会失败。首先,您的代码。更改,

for (int i = 0; i < 3; i++) {
    String line = null;
    switch (a) { 
        case 0:
            line = "Hello";
            break;
        case 1:
            line = "How are you?";
            break;
        case 2:
            line = "What are you doing?";
            break;

可以更改为

loop: for (int i = 0; i < 3; i++) {
    String line = null;
    switch (a) { 
        case 0:
            line = "Hello";
            break loop;
        case 1:
            line = "How are you?";
            break loop;
        case 2:
            line = "What are you doing?";
            break loop;

现在,第二个行为将是失败。可能看起来像,

switch (a) {
case 0: case 2: case 4: case 6: case 8:
    System.out.println("even < 10");
    break;
case 1: case 3: case 5: case 7: case 9:
    System.out.println("odd < 10");
    break;
}
© www.soinside.com 2019 - 2024. All rights reserved.