我是java初学者,我编写了一个代码,用户输入一个数字,但如果他写一个字符串而不是整数,这是一个错误,我如何控制错误以向用户显示消息?错误如下:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Main.main(Main.java:21)
Process finished with exit code 1
这是我的代码:
import java.util.Scanner;
import java.util.ArrayList;
public class Main extends MyZoo {
public static void main(String[] args) {
System.out.println("1.View all available zoo animals");
Scanner input = new Scanner(System.in);
System.out.print("Write Here: ");
int UserInput = input.nextInt();
while (true) {
try
{
return input.nextInt();
}
catch (InputMismatchException e)
{
input.next();
System.out.print("That’s not an integer. Try again: ");
}
}
}
}
最佳答案
您的 try
catch
看起来不错,但您应该将第一个 int UserInput = input.nextLine()
放在 try 中
当然。
也许你想要这样的东西:
System.out.println("1.View all available zoo animals");
Scanner input = new Scanner(System.in);
while (true) {
try
{
System.out.print("Write Here: ");
int UserInput = input.nextInt();
System.out.println("Your input: " + UserInput);
}
catch (InputMismatchException e)
{
input.next();
System.out.print("That’s not an integer. Try again: ");
}
}
关于java - 用户输入字符串而不是整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61433579/