如何验证对扫描仪的输入是否为整数?

问题描述 投票:2回答:2
System.out.println("Enter your age here:");
setAge(sc.nextInt());

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

我已经尝试过使用do-while,但似乎没有用。

我是初学者。非常感谢您的帮助。

谢谢!

java int java.util.scanner
2个回答
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
}

0
投票

以下块将满足您的需求:

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

我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.