java - 如何在 Java 中为 5x5 二维数组正确使用制表符空间?

我希望我的 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/

相关文章:

regex - 如何验证用户输入中的 Perl 正则表达式?

reactjs - Next.js 应用程序是 SPA 还是单页应用程序?

python - 将多列的不同值组合成 Polars 中的一列

javascript - 遍历对象数组并获得新的对象数组

java - Spring Boot 服务层 : Unit or Integration tests

python - 仅当 Pandas 中的所有值均为 0 时,才将 0 替换为选定列的 NaN

c++ - 如何直接从输入流中向集合中插入值?

python - 如何在 python 中删除表的某些行?

sql - 在 exec 中声明变量会改进 SQL 查询计划吗?

.net-core - SSE 和 AVX 的 MoveMask 的目的是什么