首页 > 解决方案 > 当用户没有在数组中输入任何数字或在数组中输入太多数字时打印出错误消息

问题描述

你好 java 专业人士和专家,我遇到的第一个问题是在我的程序中实现一个代码,当用户没有输入任何数字并且数组为空时,它会告诉用户“没有输入数字”。

我遇到的第二个问题是如果用户输入的数字过多,则执行代码,发出错误消息,指出已超出数组的大小;然后打印出下一行输入的数字。

到目前为止,这是我的代码:

 import java.util.Scanner;

     public class FunWithArrays
    {
        public static void main(String[] args)
        {
            final int ARRAY_SIZE = 10; // Size of the array

            // Create an array.
            int[] numbers = new int[ARRAY_SIZE];

            // Pass the array to the getValues method.
            getValues(numbers);

            System.out.println("Here are the " + "numbers that you entered:");

            // Pass the array to the showArray method.
            showArray(numbers);
        }

        public static void getValues(int[] array)
        {
            // Create a Scanner objects for keyboard input.
            Scanner keyboard = new Scanner(System.in);

            System.out.println("Enter a series of " + array.length + " numbers.");

            // Read the values into the array
            for (int index = 0; index < array.length; index++)
            {
                System.out.print("Enter the number " + (index + 1) + ": ");
                array[index] = keyboard.nextInt();
            }
        }

    public static void showArray(int[] array)
    {
        // Display the array elements.
        for (int index = 0; index < array.length; index++)
            System.out.print(array[index] + " ");
    }
}

我想知道您的专业人士或专家是否对如何在不更改程序中的任何代码的情况下解决此问题有任何建议?我的教授指示我为这个问题做一个 do-while 循环,但不知道如何为它创建代码......有什么建议吗?

标签: javaarrayscommand-linejavac

解决方案


推荐阅读