【发布时间】:2019-04-18 09:16:35
【问题描述】:
所以我试图在某些地方用字符 * 填充数组以获取模式。数组的大小(行和列)相同,由用户输入决定。必须是奇数并且介于 3 和 11 之间,因此例如,如果他们放入 5,则它会生成 5 x 5 数组。无论如何,我正在尝试反转我从
获得的输出-----------
*
*
*
*
*
----------- to get
-----------
*
*
*
*
*
----------- but instead I get
-----------
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
----------- I used 5 as the size example here in case that helps
问题是我的循环似乎不能正常工作,至少我认为。这是代码
public static void main (String [] args) {
int dimension = findDimension();
char [] [] array2d = new char [dimension] [dimension];
char star = '*';
array2d = leftDiagonal(star, dimension);
print(array2d);
array2d = rightDiagonal(star, dimension);
System.out.println();
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;
}
public static void print(char [] [] arrayParam) {
for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++) {
System.out.print("-");
}
System.out.println();
for(char[] row : arrayParam)
{
for(char c : row)
System.out.print(" " + c);
System.out.printf("\n");
}
for (int hyphen = 0; hyphen < (arrayParam.length*2)+1; hyphen++) {
System.out.print("-");
}
}
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)
leftD[i][j] = starParam;
else
leftD[i][j] = ' ';
}
}
return leftD;
}
我认为问题出在此处,因为它决定了数组中保存的内容
public static char [] [] rightDiagonal(char starParam, int dimenParam) {
char [] [] rightD = new char [dimenParam] [dimenParam];
for (int i = 0; i < dimenParam; i++){
for (int j = 0; j < dimenParam; j++) {
rightD[i][j] = ' ';
// I fill all the element spaces with blanks first then put in the *
// If there's another way to do It I'd like to know
}
}
for (int i = 0; i < dimenParam; i++){
for (int j = rightD.length-1; j >= 0; j--) {
rightD[i][j] = starParam;
}
}
return rightD;
}
【问题讨论】:
-
找对角线使用条件
i + j = rightD.length-1
标签: java arrays for-loop format output