在Java中进行while循环时,如何使此代码循环直到用户输入数值?

时间:2019-02-04 10:00:18

标签: java loops while-loop

我尝试过执行do while循环并得到一个无限循环,而不是在catch部分重复错误消息。在用户输入数值之前,如何使此代码循环播放?

  try {
    System.out.print("How many people are in your group? ");
    int group = sc.nextInt(); 
    System.out.println("Okey, " + group + " people");
 }  
 catch (InputMismatchException e) {
    System.out.println("Error, please enter a numerical value");
 } 

2 个答案:

答案 0 :(得分:0)

只需将while(true)循环添加到您的代码中即可:

 public static int getInt(Scanner sc) {
    while(true) {
        try {
            System.out.print("How many people are in your group? ");
            int group = sc.nextInt(); 
            System.out.println("Okey, " + group + " people");
            return group;
        } catch (InputMismatchException e) {
            System.out.println("Error, please enter a numerical value");
        }
    }
 }

答案 1 :(得分:0)

由于do实例(while)的内部缓冲区使您保持错误,所以您的代码(用Scanner ... sc语句包围)将陷入无限循环。 )在发生InputMismatchException时输入。 您可以使用Scanner.next方法(无论其值是什么,都读取String)和Integer.parseInt进行转换来重写逻辑:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Integer group = null;
    do {
        try {
            System.out.print("How many people are in your group? ");
            String input = sc.next();
            group = Integer.parseInt(input);
            System.out.println("Okey, " + group + " people");
        } catch (NumberFormatException e) {
            System.out.println("Error, please enter a numerical value");
        }
    } while(group == null);
}