因此,该程序应该根据用户输入在3到11的大小之间生成一个奇数大小的数组,然后在特定位置用一个字符填充该板上以获取图案.一切都进行得很好,直到我尝试返回的数组给了我2个超出范围的异常,即使我将循环设置为小于尺寸.我在这里以5为例,尝试得到5 x 5的数组.这是主要的.
public static void main (String [] args) {
int dimension = findDimension();
char [] [] array2d = new char [dimension] [dimension];
char star = '*';
array2d = leftDiagonal(star,dimension); // Get out of bounds here
print(array2d);
}
public static int findDimension() {
int dimension = 0;
Scanner keybd = new Scanner(System.in);
do {
System.out.print("Enter an odd integer between 3 and 11 please: ");
dimension = keybd.nextInt();
} while (dimension%2 == 0);
return dimension; // Everything seems fine here,no errors
}
打印数组的方法
public static void print(char [] [] arrayParam) {
System.out.println("-----------");
System.out.println(arrayParam);
System.out.println("-----------");
}
设置模式“ leftDiagonal”的方法
public static char [] [] leftDiagonal(char starParam,int dimenParam) {
char [] [] leftD = new char [dimenParam] [dimenParam];
for (int i = 0; i < dimenParam; i++){
for (int j = 0; i < dimenParam; j++) {
leftD [i][j] = starParam; // Gets error here
}
}
return leftD;
}
输出应为
-----------
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
-----------
从技术上讲应该是
-----------
*
*
*
*
*
-----------
但此刻我只想获取任何输出.我本来打算用空格”填充所有空格,然后用字符填充我需要的空格,但是我什至无法使数组先打印出来.谢谢任何愿意提供帮助的人.
最佳答案
由于内部循环条件而发生错误.
原文链接:https://www.f2er.com/java/532914.htmlpublic static char[][] leftDiagonal(char starParam,int dimenParam) {
char[][] leftD = new char[dimenParam][dimenParam];
for (int i = 0; i < dimenParam; i++) {
for (int j = 0; j < dimenParam; j++) { // i -> j
leftD[i][j] = starParam; // Gets error here
}
}
return leftD;
}
public static char[][] leftDiagonal(char starParam,int dimenParam) {
char[][] leftD = new char[dimenParam][dimenParam];
for (int i = 0; i < dimenParam; i++) {
for (int j = 0; j < dimenParam; j++) {
if(i==j) {
System.out.print(starParam);
} else {
System.out.print(" ");
}
}
System.out.println();
}
return leftD;
}