java 执行保持超时,这是'做,而'循环

f1tvaqid  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(114)

我试着在IDE上运行它,但它就是不运行。只有输入数字0才能运行它。它不能离开循环吗?

public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       int number = scanner.nextInt();
       do {
            switch(number) {
                case 1:
                    System.out.println("Language selection");
                    break;
                case 2:
                    System.out.println("Customer support");
                    break;
                case 3:
                    System.out.println("Check account balance");
                    break;
                case 4:
                    System.out.println("Check loan balance");
                    break;
           } 
       }
       while(number != 0);
       System.out.println("Exit");
   }
}
0h4hbjxa

0h4hbjxa1#

number的初始化应该在前面完成。下面是代码:

import java.util.Scanner;

public class Main1 {

        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int number;
            do {
                number = scanner.nextInt();
                switch(number) {
                    case 1:
                        System.out.println("Language selection");
                        break;
                    case 2:
                        System.out.println("Customer support");
                        break;
                    case 3:
                        System.out.println("Check account balance");
                        break;
                    case 4:
                        System.out.println("Check loan balance");
                        break;
                }
            }
            while(number != 0);
            System.out.println("Exit");
        }
    }
2wnc66cl

2wnc66cl2#

两个变化:将scanner.nextInt()行移动到do内部,并将while条件从number != 0更改为number < 1 || number > 4

Scanner scanner = new Scanner(System.in);
        int number;
        do {
            number = scanner.nextInt();
            switch(number) {
                case 1:
                    System.out.println("Language selection");
                    break;
                case 2:
                    System.out.println("Customer support");
                    break;
                case 3:
                    System.out.println("Check account balance");
                    break;
                case 4:
                    System.out.println("Check loan balance");
                    break;
            }
        }
        while(number < 1 || number > 4);
        System.out.println("Exit");

相关问题