javaswing

Calculating Score [Java procedural]


My program keeps adding up the score for each player, rather than keeping it seperate 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.

Upfront thanks!

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);

Solution

  • Reset the score variable within your loop and then place it in the corresponding element of playerscore. Here's the code:

    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!");
    
    
        score = 0; //reset the score variable
        /* --------------------------- 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;
                System.out.println("\nPlayer"+(i)+ "Name:"+name[i]+"\tScore"+score);
            }
            else{
                JOptionPane.showMessageDialog(null,"Wrong!");
            }
        } // End for loop for Question
        playerscore[i] = score; //assign the score for each player
    }
    

    Then whenever you want the score for name[i] you can just print playerscore[i]