如何停止while循环无限运行? [英] How do I stop while loop from running infinitely?

查看:222
本文介绍了如何停止while循环无限运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法弄清楚如何阻止while循环无限重复.我正在使用hasNextInt来检查用户输入是否为int.如果未输入int,则循环将无限重复.

Can't figure out how to stop this while loop from repeating infinitely. I'm using hasNextInt to check if user input is an int. If an int is not entered the loop repeats infinitely.

public static void validatingInput(){
    Scanner scan = new Scanner(System.in);

    boolean valid = false;
    int userNumber = 0;

    while(!valid) { 
    System.out.println("Enter number between 1 and 20: ");

    if (scan.hasNextInt()) {    
    userNumber = scan.nextInt();
    valid = true;   
    } else 
        System.out.print("Not an int. ");
    }

}

推荐答案

您需要使用扫描仪中的令牌,才能读取下一个令牌:

You need to consume a token from a scanner in order to allow it to read the next token:

while (!valid) { 
    System.out.println("Enter number between 1 and 20: ");

    if (scan.hasNextInt()) {    
        userNumber = scan.nextInt();
        valid = true;   
    } else 
        System.out.print("Not an int. ");
        scan.next(); // Skip a token
    }
}

这篇关于如何停止while循环无限运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆