Scoring system and Arrays

3.6k Views Asked by At

My program keeps adding up the score for each player, rather than keeping it separate for example if first player gets 3/5 and the second gets 2/5 the score display for the second player will be 5. I know the answer is probably very simple however I'm not able to find it within the code.

public static void questions(String[] question, String[] answer, int n) {

    String[] name = new String[n];  // Player Names
    int[] playerscore = new int[n]; // Argument for Score
    String[] que = new String[question.length]; //Questions for Loops
    int score = 0; // Declare the score

    /* --------------------------- For loop for number of players --------------------------- */
    for (int i = 0; i < n; i++) {
        name[i] = JOptionPane.showInputDialog("What is your name player" + (i + 1) + "?");
        JOptionPane.showMessageDialog(null, "Hello :" + name[i] + " Player number " + (i + 1) + ". I hope your ready to start!");

        /* --------------------------- Loop in Loop for questions --------------------------- */
        for (int x = 0; x < question.length; x++) {
            que[x] = JOptionPane.showInputDialog(question[x]);

            if (que[x].equals(answer[x])) {
                score = score + 1;
            } else {
                JOptionPane.showMessageDialog(null, "Wrong!");
            }

        } // End for loop for Question
        playerscore[i] = score;
        System.out.println("\nPlayer" + (i) + "Name:" + name[i] + "\tScore" + score);
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

You will need to reset the score to 0 before each player starts.

Add this after the loop for each player:

score = 0;

Alternatively you could increment the score directly in the array. Just change:

score = score + 1;

to:

playerscore[i] = playerscore[i] + 1;

or simply:

playerscore[i]++;
0
On

Assign score=0 after the line

playerscore[i] = score;

Every each and every player is assigned with his score in inner loop. Since score is declared as instance variable it will not differentiate between two different players. In order to have each and every individual player with his own scores, assign score with zero as soon as questions exceeds.