Java 如何验证扫描仪的输入是否为int?

Java 如何验证扫描仪的输入是否为int?,java,int,java.util.scanner,Java,Int,Java.util.scanner,如何验证用户的年龄不是字符或负数? 理想情况下,如果用户输入的不是int,程序将再次请求输入 我试着用了一段时间,但似乎不起作用 我是初学者。非常感谢您的帮助 谢谢 使用sc.nextInt()执行的操作将只允许用户输入int,或者程序将抛出InputMismatchException(因此该部分的行为符合您的要求)。如果要确保数字不是负数,请执行以下操作: System.out.println("Enter your age here:"); setAge(sc.nextInt()); Sy

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

我试着用了一段时间,但似乎不起作用

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


谢谢

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

System.out.println("Enter your age here:");
setAge(sc.nextInt());
System.out.println(“在此处输入您的年龄:”);
而(!sc.hasnetint()){
System.out.println(“请输入一个整数”);
sc.next();
}
int age=sc.nextInt();
如果(年龄<0){
//如果数字是负数,你想怎么做
//如果你在程序的这一部分处于循环中,
//您可以使用continue关键字跳回循环的开头并
//让用户再次输入他们的年龄。
//只需给他们提示“输入的号码无效,请再试一次”之类的信息或类似的信息
}
否则{
设置(年龄);
//继续执行
}

以下块将执行您需要的操作:

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年龄;
System.out.println(“请输入一个整数”);
while(true){
试一试{
age=scan.nextInt();

if(age)这是否回答了您的问题?谢谢!但是如果用户输入了一个字符呢?正如我所提到的,当您使用
sc.nextInt()
时,如果有人输入一个字符而不是一个int,那么程序将抛出一个
inputmaschException
。如果您希望用户输入字符串或字符的类型,那么您将使用
sc.next()
sc.nextLine()
。仍然有点混乱。我正在尝试:
尝试{System.out.println(“输入您的年龄”);age=sc.nextInt();}catch(InputMismatchException异常){System.out.println(“请输入有效数字!”;age=sc.nextInt();}
但仍不起作用,程序会显示“请输入有效数字!”如果用户输入的任何内容不是有效的int。应该可以。您不喜欢正在发生的内容,这是如何表现的?哪个部分不起作用?输出后,请输入一个有效的数字!我得到一个InputMismatchException,它崩溃了,不允许我输入任何内容
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);