gpt4 book ai didi

java - 用户输入字符串而不是整数

转载 作者:行者123 更新时间:2023-12-01 17:10:20 25 4
gpt4 key购买 nike

我是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com