Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 196
  • Last Modified:

Arrays

Trying to make this program multi-player. At the beginning of the main method I want to prompt for number of players. Then create an array of this size to hold doubles. This will hold each players percentage correct.
Using a for loop around the rest of the main method to loop as many times as there are players. Just before the end of the for loop  store that players correct percentage in the array. After the for loop  at the end of the main method put another for loop that reads the array and displays the percentages for each player.

I'm also wondering why my non-numeric data entry code doesn't work properly once you select an option and after going to the main screen if you enter non-numeric data it goes straight to the addition screen.

Code so far without arrays.

import javax.swing.JOptionPane; // Needed for JOptionPane
import java.util.Random;
 
public class KidsCalc
  {
  //Initialise result & count to 0
  public static int result = 0;
  public static int count = 0;
  public static int correct = 0;
 
 
  public static void main(String[] args)
    {
       
       int userChoice = 0;
       double playerChoice = 0;
       String userChoiceStr;
       String playerChoiceStr;
       
              playerChoiceStr = JOptionPane.showInputDialog(null,
                        "How many players?");
              playerChoice = Double.parseDouble(playerChoiceStr);
             
                 do
          {            
              // user input prompt
               userChoiceStr =  JOptionPane.showInputDialog(null,
                       
                          "1. Practice addition\n"
                        + "2. Practice subtraction\n"
                        + "3. Practice multiplication\n"
                        + "4. Quit the program\n"
                        + "\n"
                        + "Enter your choice",
                       
                        "Enter your choice",
                        JOptionPane.QUESTION_MESSAGE);
                        // keeps track of wrong entry
                        try
                        {
                         userChoice = Integer.parseInt(userChoiceStr);
                      }
                         catch (NumberFormatException e)
                       {
                        }
       // switch statement to count user score                    
       switch (userChoice)
       {
       case 1:    
          ++count;
          addition ();
          break;
       case 2:
           ++count;
           subtraction ();
           break;
       case 3:
           ++count;
           multiplication ();
            break;
       case 4:        
            break;
        default:
         // prompt if user doesn't enter a number between 1-4  
        JOptionPane.showMessageDialog(null,
                            "Please enter a number between 1 and 4",
                            "Wrong entry",
                            JOptionPane.ERROR_MESSAGE);      
          }
 }
       // returns your percentage if input not equal to 4
        while ( userChoice != 4 );

    JOptionPane.showMessageDialog ( null ,"You got " +
                                  (result / count) + "% right!!"  );
                                 
// Ends program
  System.exit(0);
 }
 
 
  public static void addition()
    {        
        boolean isNum = true;
        int additionData = 0;
        int genNumOne, genNumTwo;
        String selectAddition;  
   
       // generates 2 random numbers between 0 and 9
        genNumOne = (int) (Math.random() * 9) + 0;
        genNumTwo = (int) (Math.random() * 9) + 0;
     
        selectAddition = JOptionPane.showInputDialog("What is" + " " + genNumOne +
                                            " " + "plus" + " " + genNumTwo + "?");    
        try
        {        
            additionData = Integer.parseInt(selectAddition);
       
        }
        catch (NumberFormatException e)
        {
            isNum = false; //keeps track of wrong entry
        }
   
       if ( additionData == (genNumOne + genNumTwo) )
        {
           
           result = result + 100;
           correctAnswer() ;  
        }
        else
            if (isNum == true)
            {
        incorrectAnswer() ;
       
    }
        else // if we have the wrong entry
        {
              JOptionPane.showMessageDialog(null,
              "Please enter a number between 1 and 4",
                                        "Wrong entry",
                JOptionPane.ERROR_MESSAGE);
               
            isNum = true;                                    
     }
}

 
    public static void subtraction()
    {      
        boolean isNum = true;
        int subtractionData = 0;
        int genNumOne, genNumTwo;
        String selectSubtraction;  
   
       
        genNumOne = (int) (Math.random() * 9) + 0;
        genNumTwo = (int) (Math.random() * genNumOne) + 0;
        // makes sure first random number is greater than second
   
        selectSubtraction = JOptionPane.showInputDialog("What is" + " " + genNumOne +
                            " " + "minus" + " " + genNumTwo + "?");    
        try
        {        
            subtractionData = Integer.parseInt(selectSubtraction);
       
        }
        catch (NumberFormatException e)
        {
            isNum = false; // keeps track of wrong entry
        }
   
       if ( subtractionData == (genNumOne - genNumTwo) )
       {
           
           result = result + 100;
           correctAnswer() ;  
        }
        else
            if (isNum == true)
            {
        incorrectAnswer() ;
       
    }
        else // if we have the wrong entry
        {
              JOptionPane.showMessageDialog(null,
              "Please enter a number between 1 and 4",
                                        "Wrong entry",
                JOptionPane.ERROR_MESSAGE);
               
            isNum = true;                                    
     }
}
       
 
    public static void multiplication()
    {
        boolean isNum = true;
        int multiplicationData = 0;
        int genNumOne, genNumTwo;
        String selectMultiplication;  
         
        genNumOne = (int) (Math.random() * 9) + 0;
        genNumTwo = (int) (Math.random() * 9) + 0;
   
        selectMultiplication = JOptionPane.showInputDialog("What is" + " " + genNumOne +
                                                 " " + "times" + " " + genNumTwo + "?");    
        try
        {        
            multiplicationData = Integer.parseInt(selectMultiplication);
       
        }
        catch (NumberFormatException e)
        {
            isNum = false; // keeps track of wrong entry
        }
   
       if ( multiplicationData == (genNumOne * genNumTwo) )
       {
           
           result = result + 100;
           correctAnswer() ;  
        }
        else
            if (isNum == true)
            {
        incorrectAnswer() ;
       
    }
        else // if we have the wrong entry
        {
              JOptionPane.showMessageDialog(null,
              "Please enter a number between 1 and 4",
                                        "Wrong entry",
                JOptionPane.ERROR_MESSAGE);
               
            isNum = true;                                    
     }
}
   

   
    public static void correctAnswer()
{

    String[] arrGood = { "Very good!",  "Well done", "Great!" };
    Random randGood = new Random();
   
    int new_rand_index = randGood.nextInt( arrGood.length );
   String message = arrGood[ new_rand_index ];
   JOptionPane.showMessageDialog(null, message,
                    "Good Answer",
                    JOptionPane.INFORMATION_MESSAGE);
                   
                   

    }



    public static void incorrectAnswer()
{

    String[] arrBad = {  "Sorry that was incorrect.", "Better luck next time",  "Bad luck" };
    Random randBad = new Random();

   
    int new_rand_index = randBad.nextInt( arrBad.length );
   String message = arrBad[ new_rand_index ];
   JOptionPane.showMessageDialog(null, message,
                    "Bad Answer",
                    JOptionPane.INFORMATION_MESSAGE);

     
   
      }
}


0
DeafBox
Asked:
DeafBox
  • 6
  • 2
1 Solution
 
imladrisCommented:
The first part looks like a set of instructions to make the program multiplayer. Just follow the instructions. If you have difficulties, please show the code you have so far, and explain the problem you are having.

As for the final question: "Why does non-numeric entry go straight to addition?" I can imagine a sequence in which this would occur. Consider your main loop (with only the relevant bits shown):

       int userChoice = 0;
      ...      
      do
          {   // user input prompt
               userChoiceStr =  JOptionPane.showInputDialog(null,....   ..... );
                        // keeps track of wrong entry
                        try
                        {
                         userChoice = Integer.parseInt(userChoiceStr);
                      }
                         catch (NumberFormatException e)
                       {
                        }
       // switch statement to count user score                    
       switch (userChoice)
       {
       case 1:    
          ++count;
          addition ();
          break;
     ....
     ....
           }
 }
       // returns your percentage if input not equal to 4
        while ( userChoice != 4 );

Imagine the following sequence:
UserChoice is set to 0
User inputs 1 (to practice addition)
string is converted to numeric 1 with parseInt in try/catch block and assigned to UserChoice
switch goes to case 1 which call addition method
while inspects UserChoice and finds it to be not 4, so goes back to the top
user now inputs non-numeric data
string is not converted; code goes to the catch block; UserChoice is NOT set
switch goes to case 1

So, you can see that any occurence of non-numeric data entry *after* the first loop, will simply repeat the last selection.
0
 
DeafBoxAuthor Commented:
Is there another way to stop non-numeric data being entered without try/catch block?
0
 
DeafBoxAuthor Commented:
I'm stuck on the array.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
DeafBoxAuthor Commented:
OK this is what I have.

I still have a few bugs like when I press cancel i get a random error, and say you have 2 players.. the first player when you press 4 to quit and get score it comes up with another error but then works fine for the 2nd player. My main problem is with my menu not showing what player is now currently playing in the menu..all i have is the number of players showing in menu.

import javax.swing.JOptionPane;
import java.util.Random;
import java.util.Vector;

public class Wtf
  {
  //Initialise result & count to 0
  public static int result = 0;
  public static int count = 0;
 
 
  public static void main(String[] args)
    {
       int  i=0;
       int userChoice = 0;
       double playerChoice = 0;
       String userChoiceStr;
       String playerChoiceStr;
    //    Vector v = new Vector ();
        double v[] = new double[50];

             
         playerChoiceStr = JOptionPane.showInputDialog(null,
                        "How many players?");
        playerChoice = Double.parseDouble (playerChoiceStr);
       
    for (i =0; i < (int)playerChoice ; i++)
    {

          do
          {          
              // user input prompt
               userChoiceStr =  JOptionPane.showInputDialog (null,
                             
                        "Player" + " " + playerChoiceStr  + "\n" +
                                         
                          "1. Practice addition\n"
                        + "2. Practice subtraction\n"
                        + "3. Practice multiplication\n"
                        + "4. Quit the program\n"
                        + "\n"
                        + "Enter your choice",
                     
                        "Enter your choice",
                        JOptionPane.QUESTION_MESSAGE);
                        // keeps track of wrong entry
 
                         userChoice = Integer.parseInt(userChoiceStr);
 
       // switch statement to count user score                  
       switch (userChoice)
       {
       case 1:  
          ++count;
          addition ();
          break;
       case 2:
           ++count;
           subtraction ();
           break;
       case 3:
           ++count;
           multiplication ();
            break;
       case 4:      
            break;
        default:
         // prompt if user doesn't enter a number between 1-4
        JOptionPane.showMessageDialog(null,
                            "Please enter a number between 1 and 4",
                            "Wrong entry",
                            JOptionPane.ERROR_MESSAGE );    
          }
    } while ( userChoice != 4 );  // returns your percentage if input not equal to 4
 
String str = "Got " + (result / count) + "% right!! \n";
v[i]= (result/count);
System.out.println ( v[i]);
JOptionPane.showMessageDialog ( null , "You " + str );
//v.add(str);

}

String showAll = "";
    i=0;

    /*java.util.Enumeration enum = v.elements ();

    while ( enum.hasMoreElements())
        {
         showAll = showAll + "Player "+ ++i +" : " + enum.nextElement () ;
        }
     */

for (i =0; i < (int)playerChoice ; i++)
    {
    showAll = showAll + "Player "+ (i+1) +" : got " + v[i] +" % right!! \n";
    }

JOptionPane.showMessageDialog ( null , showAll );
                               
// Ends program
  System.exit(0);
 }
 

 

  public static void addition()
    {      
       
        int additionData = 0;
        int genNumOne, genNumTwo;
        String selectAddition;
 
       // generates 2 random numbers between 0 and 9
        genNumOne = (int) (Math.random() * 9) + 0;
        genNumTwo = (int) (Math.random() * 9) + 0;
   
        selectAddition = JOptionPane.showInputDialog ("What is" + " " + genNumOne +
                                            " " + "plus" + " " + genNumTwo + "?");  
                                           
        additionData = Integer.parseInt(selectAddition);
     
     
       if (additionData == (genNumOne + genNumTwo) )
       {
           correctAnswer() ;
           result = result + 100;
           
        }
        else
            {
        incorrectAnswer() ;
     
                                 
     }
}
 
 
    public static void subtraction()
    {    
       
        int subtractionData = 0;
        int genNumOne, genNumTwo;
        String selectSubtraction;
 
     
        genNumOne = (int) (Math.random() * 9) + 0;
        genNumTwo = (int) ( Math.random() * genNumOne) + 0;
        // makes sure first random number is greater than second
 
        selectSubtraction = JOptionPane.showInputDialog("What is" + " " + genNumOne +
                            " " + "minus" + " " + genNumTwo + "?");  
                           
                           
        subtractionData = Integer.parseInt(selectSubtraction);
     
   
 
       if (subtractionData == (genNumOne - genNumTwo) )
       {
           correctAnswer() ;
           result = result + 100;
           
        }
        else
            {
        incorrectAnswer() ;
     
                                 
     }
}
     
 
 
    public static void multiplication()
    {
       
        int multiplicationData = 0;
        int genNumOne, genNumTwo;
        String selectMultiplication;
       
        genNumOne = (int) (Math.random() * 9) + 0;
        genNumTwo = (int) (Math.random() * 9) + 0;
 
        selectMultiplication = JOptionPane.showInputDialog("What is" + " " + genNumOne +
                                                 " " + "times" + " " + genNumTwo + "?");  
     
                                               
        multiplicationData = Integer.parseInt(selectMultiplication);
     
   
 
       if ( multiplicationData == (genNumOne * genNumTwo) )
       {
           correctAnswer() ;
           result = result + 100;
           
        }
        else
            {
        incorrectAnswer() ;
     
                                 
     }
}
 
 
 
    public static void correctAnswer()
{
 
    String[] arrGood = { "Very good!",  "Well done", "Great!" };
    Random randGood = new Random();
 
    int new_rand_index = randGood.nextInt( arrGood.length );
   String message = arrGood[ new_rand_index ];
   JOptionPane.showMessageDialog(null, message,
                    "Good Answer",
                    JOptionPane.INFORMATION_MESSAGE);
                 
                 
 
    }
 
 
 
    public static void incorrectAnswer()
{
 
    String[] arrBad = {  "Sorry that was incorrect.", "Better luck next time",  "Bad luck" };
    Random randBad = new Random();
 
 
    int new_rand_index = randBad.nextInt( arrBad.length );
   String message = arrBad[ new_rand_index ];
   JOptionPane.showMessageDialog(null, message,
                    "Bad Answer",
                    JOptionPane.INFORMATION_MESSAGE);
 
   
 
      }
}
0
 
DeafBoxAuthor Commented:
Ah lol, i miss typed a variable name.
0
 
DeafBoxAuthor Commented:
Nope I was wrong, still not working..
0
 
DeafBoxAuthor Commented:
Works now just by adding "Player" + " " + (i+1)
0
 
imladrisCommented:
We're in very different time zones, so I wasn't around when you were working your way through further issues. Glad you got it sorted out.

0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

  • 6
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now