gpt4 book ai didi

java - 在Java中请求两个整数值并抛出错误

转载 作者:行者123 更新时间:2023-12-02 09:23:54 25 4
gpt4 key购买 nike

我有这个代码。它要求两个整数值。如果第一个数字不是整数,则会抛出异常并再次询问该数字。我的代码有效,但我想知道是否有更好的方法来做到这一点:

boolean validInput = false;
boolean validInput2 = false;

while (validInput == false) {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("What is the first number? ");
int firstNum = scanner.nextInt();
validInput = true;
} catch (InputMismatchException e) {
System.out.println("It's not an integer.");
}
}

while (validInput2 == false) {
try {
Scanner scanner2 = new Scanner(System.in);
System.out.print("What is the second number? ");
int secondNum = scanner2.nextInt();
scanner2.close();
validInput2 = true;
} catch (InputMismatchException e) {
System.out.println("It's not an integer.");
}
}

我想我也可以做这样的事情。正确的?

while (validInput == false) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is the first number? ");
if (scanner.hasNextInt()) {
int firstNum = scanner.nextInt();
validInput = true;
}
}

在第二个示例中,当调用 hasNextInt() 方法时,扫描器会等待一个有意义的值,如果条件成立,nextInt() 被调用,但 nextInt() 不再等待输入。 nextInt() 如何知道执行条件时输入的值是什么?

最佳答案

这就是我会做的方式:

int firstNum;
int secondNum;
String num;
String errMsg = "Invalid Input - Integer Only!";

Scanner scanner = new Scanner(System.in);

while (true) {
System.out.print("What is the first number? ");
num = scanner.nextLine();
if (num.matches("\\d+")) {
firstNum = Integer.parseInt(num);
break;
}
System.out.println(errMsg);
}

while (true) {
System.out.print("What is the second number? ");
num = scanner.nextLine();
if (num.matches("\\d+")) {
secondNum = Integer.parseInt(num);
break;
}
System.out.println(errMsg);
}

System.out.println();
System.out.println("First Number: --> " + firstNum);
System.out.println("eacond Number: --> " + secondNum);

为了从用户那里获取数字输入,我更喜欢使用 Scanner.nextLine()方法与 String.matches() 结合使用方法和简单Regular Expression ("\\d+")。您不需要以这种方式捕获异常。我只是发现它更灵活。

while 循环之前声明变量,这样您就可以在 while 循环之后使用它们,或者如果您愿意,甚至可以在其他 while 循环中。一旦您获得并验证了您所需要的内容,就可以跳出循环。

关于java - 在Java中请求两个整数值并抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58478084/

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