简体   繁体   English

当要求用户在Java中循环输入一些字符串时,如何仅保留文本打印一次

[英]How to keep Text print only once when asking a user to re-enter some string in loop in Java

I want to ask user to enter a number in type String, then check if it is number and if it's not then ask again to re-enter the string. 我想让用户在String类型中输入一个数字,然后检查它是否为数字,如果不是,则再次要求重新输入该字符串。 I have a code like this: 我有这样的代码:

    System.out.print("Enter first number: ");
    firstNum = scan.next();

    while(validateNum(firstNum) == false) {
        System.out.print("Please, enter number only: ");
        firstNum = scan.next();
    }

here's the validateNum method : 这是validateNum方法:

    private static boolean validateNum(String num) {
        if (num.matches("[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?")){
            return true;
        }
        return false;
    }

But the problem is that when I test it and enter some text with spaces it prints "Please, enter a number only" as many times as many spaces are in entered string. 但是问题是,当我测试它并输入一些带有空格的文本时,它会打印“请仅输入一个数字”,这是输入字符串中出现的空格的次数。 I tried to remove spaces from string and then check it but it still gives many prints. 我试图从字符串中删除空格,然后检查它,但它仍然可以打印出许多文字。

You are using scan.next() . 您正在使用scan.next() This returns what comes before a space. 这将返回空格之前的内容。 You want scan.nextLine() to scan the entire line the user inputs 您希望scan.nextLine()扫描用户输入的整行

Here is the docs on the Scanner class and it's methods. 这是Scanner类及其方法的文档

In short: 简而言之:

next() : Scans for the next complete token next() :扫描下一个完整令牌

nextLine() : Scans the complete line nextLine() :扫描整行

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

相关问题 如何在用户登录失败时重新进入 - How to make it re-enter when user login fail 在第二个for循环中,如何使用户重新输入考试分数(如果为负)? - How to do I make the user re-enter the exam scores if its negative, in the second for loop? 如果用户输入参数之外的数字,如何循环提示用户重新输入数字 - How to loop a prompt for a user to re-enter a number if they input a number outside of the parameters 我如何要求用户重新输入他们的选择? - How can I ask the user to re-enter their choice? Java-异常处理-如何重新输入无效输入 - Java - Exception handling - How to re-enter invalid input 如果发生错误,如何提示用户重新输入值,以及如何提供继续检查工资率或退出程序的选项? - How to prompt the user to re-enter a value if a mistake was made and How to give an option to keep on checking pay rates or to exit the program.? 提示用户重新输入整数直到输入二进制数 - Prompting user to re-enter integers until binary number is entered 如果值不正确,使用户重新输入值 - make a user re-enter values if value not correct 如何继续要求用户输入正确的号码 - how to do keep asking the user to enter the right number 在循环中要求用户输入时如何忽略Java中的大小写 - How to ignore case in java when asking for user input in a loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM