如何验证 Scanner 的输入是一个 int?

How to validate that input to Scanner is an int?

System.out.println("Enter your age here:");
setAge(sc.nextInt());

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

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

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

谢谢!

您对 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
}

以下块将满足您的需要:

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);

希望对您有所帮助。