我正在学习 Java 初学者课程并研究数组。我的任务是在用户输入的两个值之间生成指定数量的随机整数。
这是我的代码:
// Variables
int amount,ur,lr,range;
System.out.println("Enter the amount of random numbers to generate::");
amount = Integer.parseInt(myInput.readLine());
System.out.println("\nEenter the upper range:");
ur = Integer.parseInt(myInput.readLine());
System.out.println("\nEnter the lower range:");
lr = Integer.parseInt(myInput.readLine());
// Create a new array that holds up to user inputted amount of variables
int[] generate = new int[amount];
// Create a range of numbers the array can randomly select as its value,
// given the user's input of the lowest and highest values available to be selected
range = (int)(Math.random() * ur) +lr;
System.out.println("\nGENERATED NUMBERS");
System.out.println("=================");
// Loop to print randomized numbers up to the amount the user inputted
for (int n=0; n < generate.length; n++){
// Give the array the value of the range
generate[amount] = range;
// Output [amount] variables
System.out.println(generate[amount]);
}
我得到的错误是
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at randomnumbers.RandomNumbers.main(RandomNumbers.java:42)
Java Result: 1
如果有人能解释为什么会发生这种情况/这意味着什么,以及如何解决,那将很有帮助。