我制作了一个包含整数值的2D数组,并想将其转换为字符串,但是我对能够放入//以获得所需输出的东西感到困惑。
public static void main(String[] args) {
final int [][] test = { {1, 6, 11, 16, 21},
{2, 7, 12, 17, 22},
{3, 8, 13, 18, 23},
{4, 9, 14, 19, 24},
{5, 10, 15, 20, 25} };
System.out.println(TwoDOneD.DownNUp(test));
public static String DownNUp(int [][] test) {
String res = "";
for (int r = 0; r < test[0].length; r++) {
for (int c = 0; c < test.length; c++) {
if (c % 2 == 1) {
//something
} else {
res += test[c][r] + " ";
}
}
}
return res;
}
我试图获得的输出就是为什么我有(c%2 == 1);在每一个奇数列中,它都应该下降,而在每个偶数列中,它都应该右退。
1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16 21 22 23 24 25
答案 0 :(得分:5)
您需要根据c % 2 == 0
public static void main(String[] args) {
final int [][] test = { {1, 6, 11, 16, 21},
{2, 7, 12, 17, 22},
{3, 8, 13, 18, 23},
{4, 9, 14, 19, 24},
{5, 10, 15, 20, 25} };
System.out.println(downUp(test));
}
public static String downUp(int [][] test) {
String res = "";
for (int c = 0; c < test[0].length; c++) {
if (c % 2 == 0) {
for (int r = 0; r < test.length; r++) {
res += test[r][c] + " ";
}
} else {
for (int r = test.length -1 ; r >=0 ; r--) {
res += test[r][c] + " ";
}
}
}
return res;
}
旁注:最好像这样使用StringBuilder
来实现:
public static String downUp(int [][] test) {
StringBuilder res = new StringBuilder();
for (int c = 0; c < test[0].length; c++) {
if (c % 2 == 0) {
for (int r = 0; r < test.length; r++) {
res.append(test[r][c]).append(" ");
}
} else {
for (int r = test.length -1 ; r >=0 ; r--) {
res.append(test[r][c]).append(" ");
}
}
}
return res.toString();
}
答案 1 :(得分:1)
我认为这是您想要的:
public static String DownNUp(int[][] test) {
String res = "";
for (int r = 0; r < test[0].length; r++) {
for (int c = 0; c < test.length; c++) {
if (r % 2 != 0) {
res += test[test.length - 1 - c][r] + " ";
} else {
res += test[c][r] + " ";
}
}
}
return res;
}