gpt4 book ai didi

java - 为什么我的数组循环越界?

转载 作者:行者123 更新时间:2023-12-01 13:53:42 26 4
gpt4 key购买 nike

代码从这里开始:

 System.out.print("Please enter number of rows: ");

rows = keyboard.nextInt();

while(rows > MAX_ROWS || 0 > rows){
System.out.print("ERROR: Out of range, try again: ");

rows = keyboard.nextInt();


}

rowsTotal = new double[rows];
positions = new double [rows][];

for(index = 0; index < rowsTotal.length; index++){
System.out.print("Please enter number of positions in row " + (char)(index+65) + " : ");
pos = keyboard.nextInt();
if(pos > MAX_POSITIONS){
System.out.print("ERROR: Out of range, try again: ");
pos = keyboard.nextInt();
}
positions[index] = new double[pos];


}

while(input != 'X'){
System.out.print("(A)dd, (R)emove, (P)rint, e(X)it : ");

input = keyboard.next().charAt(0);
input = Character.toUpperCase(input);




if(input == 'P'){
for(int index1= 0; index1 < rowsTotal.length; index1++){
System.out.print((char)(index1+65) + ": " );

for(int pos1= 0; pos1 < pos; pos1++){

**System.out.print(positions[index1][pos] + " ");**
}
System.out.print("[ " + totals + ", " + " " + averages + "]");
System.out.println();



}

}

错误消息如下:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at xxxxx.main(xxxxx.java:75)

这行代码是System.out.print(positions[index1][pos] + "");

最佳答案

阅读完整代码后,答案很简单。
a) 需要是System.out.print(positions[index1][pos1] + " ");
b) “pos”是位置数组内最后一个数组的大小。但并非所有的尺寸都相同。因此,如果较早的数组较小(例如,如果您输入 1、2、3),则较早的数组就会超出范围。您必须将 pos1 循环到 Positions[index1].length (因此将第 73 行更改为 for(int pos1= 0; pos1 < positions[index1].length; pos1++) )

关于java - 为什么我的数组循环越界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19760914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com