如何将二维数组与对应行的球队名称并列打印?
Hey there! Let's get your game summary printing team names and their scores properly aligned. First, let's break down what's causing the misalignment in your current code:
- You're hardcoding
teams[0]andteams[1]instead of linking each team name to its corresponding row in thescoresarray - The nested loop structure is printing all score rows first before trying to add the second team name, which breaks the pairing
- There's an extra semicolon after
System.out.println();that creates an unnecessary blank line
Here's the fixed version that correctly pairs each team with its score row:
Corrected Game Summary Code
// Game Summary System.out.println("Game Summary"); System.out.println("------------"); // Loop through each team and its matching score row for (int i = 0; i < teams.length; i++) { // Print the current team name System.out.print(teams[i] + ": "); // Print all scores for this team for (int j = 0; j < scores[i].length; j++) { System.out.printf("%3d", scores[i][j]); } // Move to a new line after finishing the team's scores System.out.println(); }
Key Improvements:
- We loop over
teams.length(assumingteamsandscoreshave the same length, which they should for this use case) to ensure every team gets paired with its score row - For each iteration
i, we useteams[i]for the team name andscores[i]for their corresponding scores—this keeps the pairing tight - Added a space after
teams[i] + ": "to make the output easier to read - Removed the extra semicolon that was creating unexpected blank lines
If there's a chance scores and teams might have mismatched lengths, you could add a quick check (like if (i < scores.length)) to avoid index-out-of-bounds errors, but assuming your data is structured correctly (one team per score row), this will work flawlessly.
内容的提问来源于stack exchange,提问作者John Brown
相关产品推荐
相关产品推荐

