【问题标题】:How to validate that input to Scanner is an int?如何验证扫描仪的输入是一个 int?
【发布时间】:2020-03-29 16:44:33
【问题描述】:
System.out.println("Enter your age here:");
setAge(sc.nextInt());

如何验证用户的年龄不是字符或负数? 理想情况下,如果用户输入除 int 以外的任何内容,程序会再次要求输入。

我尝试过使用 do-while,但似乎不起作用。

我是初学者。任何帮助都非常感谢。

谢谢!

【问题讨论】:

标签: java int java.util.scanner


【解决方案1】:

您对sc.nextInt() 所做的操作将只允许用户输入一个 int 或程序将抛出 InputMismatchException(因此该部分的行为方式符合您的要求)。如果您想确保数字不是负数,请执行以下操作:

System.out.println("Enter your age here:");
while (!sc.hasNextInt()) {
    System.out.println("Please enter an integer.");
    sc.next();
}

int age = sc.nextInt();

if(age < 0) {
    //do what you want if the number is negative
    //if you're in a loop at this part of the program, 
    //you can use the continue keyword to jump back to the beginning of the loop and 
    //have the user input their age again. 
    //Just prompt them with a message like "invalid number entered try again" or something to that affect
}
else {
    setAge(age);
    //continue execution
}

【讨论】:

  • 谢谢!但是如果用户输入一个字符呢?
  • 正如我所提到的,当您使用sc.nextInt() 时,如果有人输入 char 而不是 int,程序将抛出 InputMismatchException。如果您希望用户输入字符串或字符的类型,您可以使用sc.next()sc.nextLine()
  • 还是有点混乱。我正在尝试:try { System.out.println("Enter your age: "); age=sc.nextInt(); } catch(InputMismatchException exception) { System.out.println("Please enter a valid number!"); age=sc.nextInt(); } 但还是不行
  • 所以程序说“请输入一个有效的数字!”如果用户输入任何不是有效 int 的内容。那应该行得通。你不喜欢正在发生的事情是如何表现的?哪个部分不工作?
  • 输出后请输入有效数字!我得到一个 InputMismatchException 并且它在不让我输入任何内容的情况下崩溃
【解决方案2】:

以下块将满足您的需要:

int age;
System.out.println("Please enter an integer");
while (true) {
    try{
        age= scan.nextInt();
        if (age<=0) throw new Exception("Negative number");
        break;
    } catch(Exception e){
        System.out.println("Please enter a positive integer");
    }
    scan.nextLine();
}

// below just call 
setAge(age);

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 2018-05-30
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多