java - 为什么我不能让用户提示变量是数组大小?

标签 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只想要一个设定的数字,而不是用户输入的数字。有办法让它工作吗?

最佳答案

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

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

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

关于java - 为什么我不能让用户提示变量是数组大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36272732/

相关文章:

java - 为什么内部静态类会扩展外部抽象类?

java - 最大对数

java - java 统计元素出现的频率

Java数组/逆新手

javascript - 如何从 JSON 中的数组中选择名称未知的第一个属性和第一项

ruby-on-rails - Ruby:不区分大小写的数组比较

java - Hibernate、多线程和 CascadeType.ALL

java - gradle - 项目作为依赖项

java - 包含日期的单元格上的 DataFormatter 呈现两位数年份

Java 不可变对象(immutable对象)