首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我正在用java创建一个小程序,它要求用户输入5个整数并放入数组中。

我正在用java创建一个小程序,它要求用户输入5个整数并放入数组中。
EN

Stack Overflow用户
提问于 2014-02-14 04:53:39
回答 5查看 1.8K关注 0票数 0

这是我尝试过的代码,我可以将5个整数放入数组中,但我的问题是验证输入,并在不验证时给出错误消息。如果我输入了5个整数,并且它们在所需的范围内,它就可以工作,当我输入一个不在所需范围内的数字时,我会得到一条错误消息,这是我想要的,但是如果我输入一个符号或字母,我的程序就会崩溃。

代码语言:javascript
复制
import java.util.Scanner;

public class QuestionNr1 {

    public static void main(String[] args) {
        //Keyboard Initialization
        Scanner scanner = new Scanner(System.in);

        //Declare an array to hold 5 integers values
        int list[] = new int[5];
        int i = 0;
        int sum = 0;

        System.out.println("Please enter 5 numbers within the range 1 - 20, with 1 being the lowest and 20 being the highest.");
        while (i < 5) {
            //Fill the array with integers from the keyboard (range: 0 to 20).
            int value = scanner.nextInt();
            if (value >= 0 && value <= 20) {
                list[i] = value;
                i++;
            } else {
                System.out.println("Invalid input, please enter a number with the required range of 1 - 20.");
            }
        }
        for (int j = 0; j < list.length; j++) {
            int value = list[j];
        }

        double average = 0;
        for (int i1 = 0; i1 < list.length; i1++) {
            sum = sum + list[i1];
        }
        System.out.print("The sum total of your five entered numbers = " + sum);
    }
}
EN

回答 5

Stack Overflow用户

发布于 2014-02-14 04:57:43

代码语言:javascript
复制
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = Integer.MIN_VALUE;
if (scanner.hasNextInt()) int value = scanner.nextInt();
else System.out.println("Please make sure the value you entered is an integer.");
票数 2
EN

Stack Overflow用户

发布于 2014-02-14 04:55:43

您应该在假设之前检查用户是否插入了一个整数(scanner.nextInt();)。

票数 1
EN

Stack Overflow用户

发布于 2014-02-14 04:56:25

您使用的是scanner.nextInt();,因此输入的文本应该是int,如果您输入的是int,而不是其他,则会抛出exception

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21765257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档