Java: switch inside do while 循环

Java: Switch inside do while loop

我尝试进行多次随机提取,为每个输入数字打印消息,即数字系列 (4 2 17 0),其中 0 将停止代码。输出错误


public class Main {

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       int number=scanner.nextInt();
       
  int x = number;
do{switch(x) {

case 1:
      System.out.println("Language selection");
break;
case 2:
       System.out.println("Customer support");
break;
case 3:
       System.out.println("Check the balance");
break;

case 4:
       System.out.println("Check loan balance");
break;
case 0:
System.out.println("Exit");
break;
  
default:
return;

}
if (x==0)
{break;}
x++;
}

while (true);

   }
} ```
![enter image description here](https://i.stack.imgur.com/RJBYn.jpg)

![enter image description here](https://i.stack.imgur.com/wCm4p.jpg)

你可以使用Scanner#hasNextInt在整数耗尽时终止循环。

演示:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextInt()) {
            int x = scanner.nextInt();
            switch (x) {
            case 1:
                System.out.println("Language selection");
                break;
            case 2:
                System.out.println("Customer support");
                break;
            case 3:
                System.out.println("Check the balance");
                break;
            case 4:
                System.out.println("Check loan balance");
                break;
            case 0:
                System.exit(0);
            }
        }
    }
}

样本运行:

4 2 17 0
Check loan balance
Customer support

另外,请注意,您需要 break 来避免不小心掉线。在这种情况下,我没有看到 default 的任何用途,因此,我已将其从演示代码中删除。

或者,使用 do-while 循环:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x = 0;

        do {
            x = scanner.nextInt();
            switch (x) {
            case 1:
                System.out.println("Language selection");
                break;
            case 2:
                System.out.println("Customer support");
                break;
            case 3:
                System.out.println("Check the balance");
                break;
            case 4:
                System.out.println("Check loan balance");
                break;
            }
        } while (x != 0);
    }
}