输入要放在二维数组

时间:2017-02-01 19:24:36

标签: java arrays multidimensional-array

程序会提示用户输入4个玩家。然后它应该要求用户为每个玩家输入10个分数。目前我的代码方式是,它要求第一个玩家获得10个分数然后移动到第二个分数并要求获得10个分数,依此类推。我需要帮助让程序让用户在[0]然后在[1]输入玩家的分数,依此类推,直到每个玩家记录了10个分数。如果这听起来令人困惑,我可以清除任何事情。这是我到目前为止所拥有的。

package bowling;
import java.util.Scanner;

public class bowling {

    private static final int NUMBER_OF_ENDS = 10;
    private static String[] player = new String[4];
    private static int[][] scores = new int[4][NUMBER_OF_ENDS];

    public static void addPlayer() {
        Scanner input = new Scanner(System.in);
        for (int counter = 0; counter < player.length; counter++) {
            System.out.println("Enter player #" + counter + " name");
            player[counter] = input.nextLine();

        }

    }

    public static void addScores() {
        Scanner input = new Scanner(System.in);

        for (int counter = 0; counter < player.length; counter++) {
            for (int inner = 0; inner < NUMBER_OF_ENDS; inner++) {
                System.out.print("Enter the score for " + player[counter]+"---->");
                scores[counter][inner] = input.nextInt();

            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

根据我的理解,你拥有它以便程序要求一个玩家的分数,然后移动到下一个,你希望它输入一个玩家的分数,然后转移到下一个玩家,并重复这个过程。如果是这样,那么您需要做的就是在addScores方法中切换for循环。

for (int inner = 0; inner < NUMBER_OF_ENDS; inner++) {
    for (int counter = 0; counter < player.length; counter++) {
        System.out.print("Enter the score for " + player[counter]+"---->");
        scores[counter][inner] = input.nextInt();
    }
}

答案 1 :(得分:0)

好像你已经有了逻辑,不是吗?如果我理解正确,你想要控制台输出如下:

Enter the first score for player 0:
Enter the first score for player 1:
Enter the first score for player 2:
Enter the first score for player 3:
Enter the second score for player 0:
Enter the second score for player 1:
Enter the second score for player 2:
Enter the second score for player 3:
etc...

而不是像这样?

Enter the first score for player 0:
Enter the second score for player 0:
Enter the third score for player 0:
etc...
Enter the first score for player 1:
Enter the second score for player 1:
Enter the third score for player 1:
etc..

如果是这样,那只会意味着像这样切换内部和外部for循环:

for (int inner = 0; inner < NUMBER_OF_ENDS; inner++) {
        for (int counter = 0; counter < player.length; counter++) {

            System.out.print("Enter score number " + (inner + 1) + " score for " + player[counter]+"---->");
            scores[counter][inner] = input.nextInt();

        }
    }

如果我误解,请告诉我。