gpt4 book ai didi

java - 输入不匹配异常

转载 作者:太空宇宙 更新时间:2023-11-04 12:08:58 26 4
gpt4 key购买 nike

我被指示创建一个代码,该代码获取用户的前 5 个输入(双倍)并计算平均值。我唯一的问题是,如果用户输入数字以外的任何内容,则会创建异常。有人可以展示如何将此异常添加到我的代码中吗?

import java.util.*;

public class Test1
{
static Scanner userInput = new Scanner(System.in);

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

System.out.println("Please enter a number: ");
double first = numbers.nextInt();

System.out.println("Please enter a number: ");
double second = numbers.nextInt();

System.out.println("Please enter a number: ");
double third = numbers.nextInt();

System.out.println("Please enter a number: ");
double fourth = numbers.nextInt();

System.out.println("Please enter a number: ");
double fifth = numbers.nextInt();

System.out.println("The average is\t" + ((first + second + third + fourth + fifth)/5)+"\t");
}
}

最佳答案

这将处理用户输入非整数。

它还删除了未使用的静态Scanner userInput

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

int total =0;
int numberOfQuestion = 5;

for (int i = 0; i < numberOfQuestion ; i ++) {
System.out.println("Please enter a number: ");

while (!numbers.hasNextInt()) {
System.out.println("Input was not a number, please enter a number: ");
numbers.next();
}

total = total + numbers.nextInt();

}

System.out.println("The average is\t" + (total/numberOfQuestion)+"\t");
}
}

关于java - 输入不匹配异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40061133/

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