Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.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 - Fatal编程技术网

Java 如何处理错误的用户输入

Java 如何处理错误的用户输入,java,Java,我的程序要求用户输入4位数字(int类型)。目前,当用户输入数字以外的任何字符时,程序崩溃。我希望当用户输入非数字字符时,程序可以告诉用户“输入错误”,然后让用户重新输入 异常处理对此有效吗?或者有其他好方法解决这个问题吗?如果您使用的是scanner,您可以将nextInt()方法与条件hasNextInt()一起使用,该条件只能读取整数输入。看一看,例如: 摘自上述职位 Scanner sc = new Scanner(System.in); System.out.print("Enter

我的程序要求用户输入4位数字(int类型)。目前,当用户输入数字以外的任何字符时,程序崩溃。我希望当用户输入非数字字符时,程序可以告诉用户“输入错误”,然后让用户重新输入


异常处理对此有效吗?或者有其他好方法解决这个问题吗?

如果您使用的是scanner,您可以将
nextInt()
方法与条件
hasNextInt()
一起使用,该条件只能读取整数输入。看一看,例如:

摘自上述职位

Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
    while (!sc.hasNextInt()) sc.next();
    num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
Scanner sc=新扫描仪(System.in);
System.out.print(“输入数字1:”);
而(!sc.hasnetint())sc.next();
int num1=sc.nextInt();
int num2;
系统输出打印(“输入数字2:”);
做{
而(!sc.hasnetint())sc.next();
num2=sc.nextInt();
}而(num2

此外,您还可以查看扫描仪的
nextInt()

文档,查看文档应用程序崩溃时已抛出错误。您需要做的是捕获异常并处理它(向用户打印适当的消息等)。请参阅