如何在相应的行旁边打印这个2 D数组?

时间:2018-04-27 17:34:29

标签: java

    //Game Summary
    System.out.println("Game Summary");
    System.out.println("------------");

    System.out.print(teams[0] + ":");

    for (int i = 0; i < scores.length; i++) {
        for (int j = 0; j < scores[i].length; j++) {
            System.out.printf("%3d", scores[i][j]);
        }
        System.out.println();;
        System.out.print(teams[1] +":");

    }

我有一个程序要求用户提供足球比赛中每支球队的得分,并将其记录在一个双数组,得分[] []和另一个存储球队名称,球队[]的阵列中。下面还有另一种方法可以添加分数。当我运行程序时,它会打印团队[1]两次。我该如何解决?示例如下

Game Summary
------------
Ravens: 14 21  3  7

Steelers:  0  0  0  0

Steelers:Ravens:45 //(here is the problem, team[1] is printed twice)

Steelers:0

2 个答案:

答案 0 :(得分:1)

我试图重现你的情况。据我了解,您希望避免重复团队。 您可以尝试使用此解决方案:

    int[][] scores = {{14, 21, 3, 7}, {0,0,0,0}};
    String teams[] = {"Ravens", "Steelers"};
    System.out.println("Game Summary");
    System.out.println("------------");

    for (int i = 0; i < scores.length; i++) {
        System.out.print(teams[i] +":");
        for (int j = 0; j < scores[i].length; j++) {
            System.out.printf("%3d", scores[i][j]);
        }
        System.out.println();
    }

输出:

Game Summary
------------
Ravens: 14 21  3  7
Steelers:  0  0  0  0

答案 1 :(得分:0)

我会像这样写一个小班......

private static class FootballTeam
{
    private String name;
    private ArrayList<Integer> scoreList;

    public FootballTeam(String name)
    {
        this.name = name;
        this.scoreList = new ArrayList<>();
    }

    public FootballTeam(String name, int ... scores)
    {
        this.name = name;
        this.scoreList = new ArrayList<>();

        for(int score : scores)
        {
            this.scoreList.add(score);
        }
    }

    // getter and setter methods ...

    @Override public String toString()
    {
        StringBuilder builder = new StringBuilder();

        builder.append(this.name);

        for(int score : this.scoreList)
        {
            builder.append(String.format("%3i", score));
        }

        return builder.toString();
    }
}

然后你可以像这样使用它......

FootballTeam [] teams = new FootballTeam [NumberOfTeams];

// read in scores and store it in the football team objects with the setter methods

System.out.println("Game Summary");
System.out.println("------------");

for(FootballTeam team : teams)
{
    System.out.println(team.toString());
}