简体   繁体   English

用户输入时执行Do-While循环-检查输入是否为空或int(java)

[英]Do-While loop on user input - check if input is not empty or int (java)

I want the user to be repeatedly asked a question if the user input is either empty OR not an int. 我希望用户被反复询问一个问题,即用户输入是否为空或不是int。 This is what I have so far: 这是我到目前为止的内容:

        Scanner scn = new Scanner(System.in);
        do {
            System.out.print("Enter id: ");
            int id = scn.nextInt();
         } while (!scn.hasNextInt());

简单地说:

while (scanner.hasNextInt());

Try something like this: 尝试这样的事情:

boolean running = true; 布尔值运行= true;

while(running){
    String s = scn.nextLine();
    if(!(s!=""||isInt(s))){
        running = false;
    }
}

You need to implement your own isInt() function, but some google will give you this. 您需要实现自己的isInt()函数,但某些Google会为您提供此功能。

Try this removing ! 试试这个删除! :

while (scn.hasNextInt());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用do-while循环检查Java中用户的输入 - Using a do-while loop to check a User's input in Java 如何使用do-while循环再次检查用户输入? - How to use do-while loop to check user input again? Java - 通过用户输入退出 do-while 循环 - Java - get out of the do-while loop with an input of user Do-while循环不等待用户输入? - Do-while loop not waiting for user input? Do-While 循环在输入用户输入时显示很多错误(Java -OSGi Equinox in Eclipse EE - Do-While loop is showing a lot of error while entering user input (Java -OSGi Equinox in Eclipse EE Java:尝试通过do-while限制用户输入时,在while循环中进行无限循环 - Java: Infinite looping within while loop when trying to limit user input with do-while 在 do-while 循环中尝试/捕获以检查用户输入(数组) - 错误的 boolean 初始化和 position - Try / catch in a do-while loop to check user input (array) - wrong boolean initialization and position Java输入缓冲区和do-while循环行为(为什么它会检查第一个字符3次?) - Java input buffer and do-while loop behavior (why does it check first character 3 times?) 使用do-while循环将用户输入添加到ArrayList - Adding user input to ArrayList using do-while loop 在java中退出带字符串输入的do-while循环 - Exiting do-while loop with string input in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM