[英]Java Array Index Out of Bounds Exception in For-loop
I am making a program that runs a formula on the numbers inputted. 我正在制作一个对输入的数字运行公式的程序。 The first integer in the input describes the amount of lines, or integers to be used in the formula. 输入中的第一个整数描述行数,即公式中要使用的整数。 I am approaching this by calculating the answers and pushing them into an array. 我正在通过计算答案并将其推入数组来解决这一问题。 However, I am getting an array out of bounds exception in one of my for loops, and I can't figure out why. 但是,我在一个for循环中遇到了数组超出范围的异常,我不知道为什么。
Here is my main method: 这是我的主要方法:
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int[] nums = {};
int lines = scan.nextInt();
for(int i = 0; i < lines; i++){
nums[i] = potFormula(scan.next());
}
System.out.println(nums);
}
Arrays have a fixed size that can't be changed once allocated. 数组具有固定大小,一旦分配就无法更改。 You're initializing nums
to {}
, which is an empty array. 您正在将nums
初始化为{}
,这是一个空数组。 Its size will always be zero. 它的大小将始终为零。
Instead, you could use: 相反,您可以使用:
int lines = scanner.nextInt();
int[] nums = new int[lines];
Your array is too small (it has zero elements). 您的数组太小(它的元素为零)。 Here is one way to fix this: 这是解决此问题的一种方法:
int lines = scan.nextInt();
int[] nums = new int[lines];
This approach works since you know the size in advance. 因为您事先知道大小,所以这种方法有效。 If you didn't, you could use an ArrayList<Integer>
. 如果没有,则可以使用ArrayList<Integer>
。 Array lists have the ability to grow on demand. 阵列列表具有按需增长的能力。
You need to initialize the nums array to the length of the lines, 您需要将nums数组初始化为行的长度,
Like this: 像这样:
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int lines = scan.nextInt();
int[] nums = new int[lines];
for(int i = 0; i < lines; i++){
nums[i] = potFormula(scan.next());
}
System.out.println(nums);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.