[英]Array out of bounds error when running this code in Java
我在下面有以下代碼,它不斷給我一個 ArrayIndexOutOfBoundsException 錯誤。 我似乎無法發現錯誤的來源。 我知道 for 循環有問題,但它沒有出現在我身上。 我試圖將字符 1 空格從原始數組向右移動到新數組。 任何幫助表示贊賞。 謝謝。
import java.util.Arrays;
public class HW3_1N {
static final int ROWS = 8;
static final int COLS = 16;
public char[][] shiftChars(char newAr[][]) {
char[][] x = new char[ROWS][COLS];
for (int i = 0; i < newAr.length; i++) {
for (int j = 0; j < newAr[i].length; j++) {
if (newAr[i][j] < (char) 32 || newAr[i][j] > (char) 126) {
x[i][j] = (char) 32;
} else if (j >= newAr[i].length) {
int lastchar = newAr[i].length;
x[i][lastchar] = newAr[i][0];
break;
} else if (newAr[i][j] > (char) 32 || newAr[i][j] < (char) 126 || j < newAr[i].length) {
int added = j + 1;
x[i][j] = newAr[i][added];
}
}
}
return x;
}
public static void main(String[] args) {
char[][] array = new char[ROWS][COLS];
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++)
array[i][j] = (char)(i * COLS + j);
System.out.println("Original Array of characters:");
System.out.println("_______________________________");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++)
if (array[i][j] < (char) 32 || array[i][j] > (char) 126)
System.out.print("" + '\u0240' + ' ');
else
System.out.print("" + array[i][j] + ' ');
System.out.println();
}
System.out.println("_______________________________");
char[][] result = null;
HW3_1N o = new HW3_1N();
result = o.shiftChars(array);
System.out.println("\n\nNew Array from shiftChars(): ");
System.out.println("_______________________________");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++)
if (result[i][j] < (char) 32 || result[i][j] > (char) 126)
System.out.print("" + '\u0240' + ' ');
else
System.out.print("" + result[i][j] + ' ');
System.out.println();
}
System.out.println("_______________________________");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.