Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何防止用户在变量上输入错误?_Java_Inputmismatchexception - Fatal编程技术网

Java 如何防止用户在变量上输入错误?

Java 如何防止用户在变量上输入错误?,java,inputmismatchexception,Java,Inputmismatchexception,我目前正在尝试构建一个代码,以防止错误的用户输入(例如,将字符/字符串存储为整数),但我无法使其正常工作 public static void main(String[] args) { int num=0, option=0; boolean keep=true; Scanner scan = new Scanner(System.in); while(keep) { System.out.println("

我目前正在尝试构建一个代码,以防止错误的用户输入(例如,将字符/字符串存储为整数),但我无法使其正常工作

    public static void main(String[] args) {
    int num=0, option=0;
    boolean keep=true;
    
    Scanner scan = new Scanner(System.in);
    
    while(keep) {
        System.out.println("1 - Test Exception.");
        System.out.println("2 - Out.");
        
        option = scan.nextInt();
        switch(option) {
        
        case 1:
            System.out.println("Write a number: ");
            if(scan.hasNextInt()) {
                num = scan.nextInt();
            }
            else {
                System.out.println("Wrong input...");
            }
            break;
        case 2:
            keep=false;
            System.out.println("Bye !");
            break;
        }
        
    }

}
我一输入字符/字符串,代码就停止工作。异常发生在option=scan.nextInt()行中


我缺少什么?

您的输入类型是唯一的整数。您是如何传递字符串/字符值的。如果您的输入是string/char,请使用Integer.parseInt(选项)。

您希望用户输入一个
int
,但是,用户可以自由输入用户喜欢的任何内容。因此,您需要确保可以解析输入

String userInput = scan.next(); //scan the input
int value;
try {
    value = Integer.parseInt(userInput); // try to parse the "number" to int
} catch (NumberFormatException e) {
    System.out.println("Hey, you entered something wrong...");
    // now you can ask the user again to enter something
}

您可以将选项声明移动到循环中,并使用var声明它,以便可以为其分配任何内容。然后可以使用.getClass()方法检查输入是否等于num(声明为int,因此只有扫描也是int时才为true)


我稍微修改了您的代码版本,因此它现在可以使用字符/字符串。我尽量少修改

publicstaticvoidmain(字符串[]args){
int num=0,option=0;
字符串输入;
布尔保持=真;
扫描仪扫描=新扫描仪(System.in);
同时(保持){
System.out.println(“1-测试异常”);
System.out.println(“2-out”);
输入=scan.next();
试一试{
option=Integer.parseInt(输入);
} 
捕获(NumberFormatException异常){
System.out.println(“错误输入”);
继续;
}
开关(选件){
案例1:
System.out.println(“写一个数字:”);
if(scan.hasNextInt()){
num=scan.nextInt();
}
否则{
System.out.println(“输入错误…”);
}
打破
案例2:
保持=假;
System.out.println(“再见!”);
}
}
}
扫描仪现在正在使用
next()
函数,该函数将返回与enter一起提交的下一个输入的字符

在try块中,函数
Integer.parseInt(input)
检查给定字符串是否为整数,否则抛出并立即捕获
NumberFormatException。在这种情况下,
continue
语句跳过while循环中的以下代码并从头开始


因此,在try-catch块之后,您可以确定,该选项是一个整数,并且开关盒正在工作。

您不应该执行类似“hasNextInt()”的检查,在您输入它之前它没有nextInt。您缺少的是,nextInt只读取int,并不意味着读取char或strings,但异常已经准备好告诉您,那你有什么问题?嘿,谢谢你的回答!抱歉说得不够清楚。我希望当用户输入错误的数据类型时,代码不会崩溃。我确实希望变量是一个整数,但如果用户误读并输入了字符,例如,我希望代码编写类似“嘿,您输入了错误…”的内容,并让用户输入一个新的“正确”值。
x.getClass()
将始终返回
class java.lang.String
x.getClass()==String.class
将始终为真,因为
next()
返回一个
String
@Beru是的,我的错,我误读了文档。很好!谢谢!:-)
System.out.println("Write a number: ");
var x = scan.next();
if(x.getClass() == num.getClass()) {
    num = x
}
else {
    System.out.println("Wrong input...");
}