gpt4 book ai didi

java - 使用 Scanner.nextInt() 时如何处理无效输入

转载 作者:行者123 更新时间:2023-12-01 21:22:58 26 4
gpt4 key购买 nike

我是一个初学者,我编写了一个java程序,允许您输入n个数字,并且仅在输入数字-5时才显示最大值、最小值和平均值,我的程序无法正确显示,我需要一些帮助。当输入字符串而不是整数时,我想使用 try/catch 来捕获错误。

        import java.util.Scanner;
public class Average{
public static void main(String[]args){

System.out.print("Enter any integer numbers or -5 to quit:");
Scanner scan =new Scanner(System.in);
double avg = 0.0;
int number = -1;
double avg = 0.0;
double sum = 0;
int count = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;

try {
while((scan.nextInt())!= -5)
{
if (count != 0) {
avg = ((double) sum) / count;
count++;
}
if (number > max){
max = number;
}
if(number < min){
min = number;
}
catch (InputMismatchException e) {
System.out.println("please enter only integer numbers");

System.out.println("Average : " + avg);
System.out.println("maximum : " + max);
System.out.println("minimum : " + min);
}
}
}
}
}

最佳答案

为了在循环中获取整数输入、响应“退出”值并防止无效输入,我将使用类似下面的模板的内容。

请注意,到目前为止,所有答案都没有提到的一个关键问题是,仅仅捕获 InputMismatchException 还不够好。您还必须调用扫描仪对象的 nextLine() 方法来清除其缓冲区中的错误输入。否则,错误的输入将在无限循环中重复触发相同的异常。根据具体情况,您可能需要使用 next() 来代替,但要知道像 this has paths 这样的输入会生成多个异常。

代码

package inputTest;

import java.util.Scanner;
import java.util.InputMismatchException;

public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);

System.out.println("Enter integers or -5 to quit.");

boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == -5) {
done = true;
}
else {
// The input was definitely an integer and was definitely
// not the "quit" value. Do what you need to do with it.
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}

示例

Enter integers or -5 to quit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: -5
Exiting...

关于java - 使用 Scanner.nextInt() 时如何处理无效输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38830142/

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