为什么我不能让用户提示可变数据大小?

时间:2016-03-28 23:10:38

标签: java arrays

public class Sort {
    public static void main(String[] args)  { 
        int i = 1;
        Scanner input = new Scanner(System.in);
        // prompts the user to get how many numbers need to be sorted
        System.out.print("Please enter the number of data points: ");
        int data = input.nextInt();
        // this creates the new array and data sets how large it is
        int [] userArray = new int[data];
        // this clarifies that the value is above 0 or else it will not run
        if (data < 0) {
            System.out.println("The number should be positive. Exiting.");
        }
        // once a value over 0 is in, the loop will start to get in all user data
        else {
            System.out.println("Enter the data:"); 
        }

        while (i <= data) {
            int userInput = input.nextInt();
            userArray[i] = userInput;
            i++;
        }

        // this calls the sortArray method to sort the values entered
        sortArray(userArray);
        // this will print the sorted array
        System.out.println(Arrays.toString(userArray));
    }
}

我已将数组大小设置为等于用户输入的数据大小,以确定要输入的变量数量。出于某种原因,Java只需要一个设定的数字而不是用户输入的数字。有没有办法使这项工作?

3 个答案:

答案 0 :(得分:4)

首先,您的代码中存在一些错误。在使用if(data < 0)创建数组之后,您正在检查int[] userArray = new int[data]; 。你应该先检查一下。

此外,获取ArrayIndexOutOfBoundsException,因为userArray[data]不存在。数组索引从0开始,因此最后一个索引是data-1。您需要将while循环更改为while(i < data)而不是while(i <= data)

问题不在于你有data而不是10作为数组的长度。问题如上所述:你的while循环。

答案 1 :(得分:1)

你的问题是while循环。因为数组是基于0的,所以您只需要检查是否i < data。通过将其设置为&lt; =,您将超出数组长度并生成ArrayIndexOutOfBoundsException

           while (i < data) {
                int userInput = input.nextInt();
                userArray[i] = userInput;
                i++;
            }

答案 2 :(得分:0)

您对数组进行了过度索引。输入数据的更标准方法是

for ( int i=0; i < data; i++ ) {
   userArray[i] = input.nextInt();
}