[英]Array indexing issues
我正在尝试使用for循环来创建类的7个实例。 我可以循环7次,但是一旦按下Enter键,就会出现ArrayIndexOutOfBound
错误。
我的代码如下:
Data[] temperatures = new Data[7];
for(int i=1; i<=temperatures.length + 1; i++)
{
System.out.println("Please enter the temperature for day " + i);
temperatures[i] = new Data(input.nextDouble());
}
数组索引从0开始。因此,您必须以这种方式循环
for(int i=0; i < temperatures.length; i++)
这是因为数组索引以0开头,并且不得大于数组大小。 在您的情况下,它的范围是1到8 ,数组大小是7。
for(int i=0; i<temperatures.length; i++)
{
System.out.println("Please enter the temperature for day " + (i+1));
temperatures[i] = new Data(input.nextDouble());
}
ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBoundsException
extends IndexOutOfBoundsException
抛出该错误指示数组已使用非法索引访问。 索引为负或大于或等于数组的大小。
该行导致错误。
for(int i=1; i<=temperatures.length + 1; i++)
您在循环中的i应该从0开始,因为Java中的数组从0th索引开始。
这将顺利导航7次。 尝试这个
for(int i=0; i < temperatures.length; i++)
数组的索引从0开始。 在您的情况下,索引将是0到6解决方案:1.将Loop更改为for(int i = 0; i
数组索引从0开始。您的代码存在问题,您正在尝试访问不存在的第8个数组元素 。 有关更多信息,请参考Java™Tutorials-Arrays 。
您的代码应如下所示:
Data[] temperatures = new Data[7]; // Indexes 0-6 (makes a total of 7 indexes)
// Start the loop from index 0, end it to index 6 (= temperatures.lenght)
for (int i = 0; i < temperatures.length; i++) {
// Since it would sound strange to enter a temperature for day 0, notice (i+1)
System.out.println("Please enter the temperature for day " + (i+1));
temperatures[i] = new Data(input.nextDouble());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.