我希望我的 2D 数组实际输出为普通的 5x5 网格,而不是水平线或垂直线,这是我目前的代码。 (我使用字符串作为数字,因为我需要稍后用“XX”替换它们)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class assignMain {
// Global declarations.
public static Scanner choice = new Scanner(System.in);
public static String player1 = "Player 1's card:";
public static String player2 = "Player 2's card:";
public static int i;
public static int j;
public static void main (String[] args) {
// Declare list to contain used numbers.
List<Scanner> usedNums = new ArrayList<>();
usedNums.add(choice);
// Declare card 1 numbers
String[][] card1 = { {"24", "2", "8", "1", "25"},
{"12", "16", "7", "17", "15"},
{"5", "6", "20", "19", "13" },
{"14", "23", "22", "4", "3" },
{"10", "18", "11", "21", "9"} };
// Declare card 2 numbers
String[][] card2 = { {"24", "21", "17", "15", "6"},
{"10", "3", "8", "18", "20" },
{"14", "7", "16", "12", "5" },
{"25", "23", "13", "19", "11"},
{"22", "4", "9", "1", "2" } };
printCard(card1, card2);
}
public static void printCard(String[][] card1, String[][] card2) {
System.out.println(player1);
for(i = 0; i < card1.length; i++) {
for(j = 0; j < card1.length; j++) {
System.out.println(card1[i][j]);
System.out.println();
}
}
}
}
当前输出是:
Player 1's card:
24
2
8
1
25
12
16
7
17
15
5
6
20
19
13
14
23
22
4
3
10
18
11
21
9
我希望输出是什么:
Player 1's card:
24 2 8 1 25
12 16 7 17 15
5 6 20 19 13
14 23 22 4 3
10 18 11 21 9
基本上希望网格是对称的而不是完全随机的,如果可能的话我打算使用\t,如果不是那么我会接受其他不太复杂的解决方案。请谢谢。
最佳答案
试试这个。
String[][] card1 = {
{"24", "2", "8", "1", "25"},
{"12", "16", "7", "17", "15"},
{"5", "6", "20", "19", "13"},
{"14", "23", "22", "4", "3"},
{"10", "18", "11", "21", "9"}};
for (String[] row : card1) {
for (String e : row)
System.out.printf("%2s ", e);
System.out.println();
}
输出:
24 2 8 1 25
12 16 7 17 15
5 6 20 19 13
14 23 22 4 3
10 18 11 21 9
https://stackoverflow.com/questions/69870275/