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/