package test1;
import java.util.Scanner;
public class Question2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int traincars;
int maxweight;
int count = 0;
int total = 0;
maxweight = input.nextInt();
traincars = input.nextInt();
int[] trains = new int[traincars];
for(int i = 0; i < traincars; i++)
{
trains[i] = input.nextInt();
}
if (total < maxweight)
{
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
}else
{
count = count + 3;
}
System.out.println("count");
}
}
这是一个非常简单的程序,但出于某种原因,火车车厢的数据超出界限..
为什么会这样?
答案 0 :(得分:2)
问题在于:
for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
当i
等于traincars-1
时,您将访问元素i+1
,i+2
。和i+3
超出trains
数组的范围。
如果你的逻辑要求计算数组的4个连续元素的总数,那么你的for
循环应该提前停止:
for(int i = 0; i < traincars - 3; i++) {...}
答案 1 :(得分:1)
在
的最后一次迭代中 for(int i = 0; i < traincars; i++)
{
total = trains[i] + trains[i+1] + trains[i+2] + trains[i+3];
count++;
}
您尝试访问trains[i+1]
,这大于trains
数组的长度。
要使这个for
循环问题,您应该执行以下操作:
for(int i = 0; i < traincars; i++)
{
total += trains[i]; //unless of course you need something else...
count++;
}