问题描述
我目前正在尝试构建一个代码来防止错误的用户输入(例如,将字符/字符串存储为整数),但我无法使其正常工作......
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();
我错过了什么?
解决方法
您希望用户输入 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
}
,
您输入的类型只是整数,您是如何传递字符串/字符值的。如果您的输入是字符串/字符,请使用 Integer.parseInt(option)。
,我稍微修正了你的代码版本,所以它现在可以使用字符/字符串。我尽量少修改。
public static void main(String[] args) {
int num=0,option=0;
String input;
boolean keep=true;
Scanner scan = new Scanner(System.in);
while(keep) {
System.out.println("1 - Test Exception.");
System.out.println("2 - Out.");
input = scan.next();
try{
option = Integer.parseInt(input);
}
catch (NumberFormatException exception){
System.out.println("Wrong input");
continue;
}
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 !");
}
}
}
扫描仪现在正在使用 next()
函数,该函数返回通过 enter 提交的下一个输入字符。
在 try 块中,函数 Integer.parseInt(input)
检查给定的字符串是否为整数,否则抛出 NumberFormatException
并立即捕获。在这种情况下,continue
语句会跳过 while 循环中的以下代码并从头开始。
所以在 try-catch 块之后,您可以确定,该选项是一个整数,并且 switch case 工作正常。
,您可以在循环内移动选项声明并使用 var 声明它,以便您可以为其分配任何内容。然后你可以使用.getClass()方法来检查输入是否等于num(声明为int,所以只有扫描也是int时才为真)。
array([[0.,0.,0.],[0.,1.,0.]])