[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Non-numeric data

Posted on 2007-10-04
8
Medium Priority
?
206 Views
Last Modified: 2013-11-23
I want to make my input boxes only accept numeric input data. And if a user enters non-numeric data it loops the input box until they enter numeric data.

Also can someone tell me why my cancel button comes up with a compiler error.

Thankyou



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

public class Calc
  {
  //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" + " " + (i+1)
                        + "\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
                       
               
                     
               
       // 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);

JOptionPane.showMessageDialog ( null , "You " + str );


}

String showAll = "";
    i=0;

for (i =0; i < (int)playerChoice ; i++)
    {
    showAll = showAll + "Player "+ (i+1) + " " + 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
Comment
Question by:DeafBox
  • 4
6 Comments
 
LVL 8

Accepted Solution

by:
malfunction84 earned 1000 total points
ID: 20016159
I didn't see any compile errors in your code.

The first problem I saw is that you're not assigning any value to the int userChoice.  You want to parse it from the userChoiceStr, the value returned by your input dialog.

If you want to know whether or not they entered a valid number, surround your call to Integer.parseInt() with a try/catch block, like so:

try {
    userChoice = Integer.parseInt(userChoiceStr);
} catch (NumberFormatException ex) {
    // the user didn't enter a number
    userChoice = 0;
}

Since you check for a value between 1 and 4 in the switch/case, a value of 0 will be processed in the "default" case, and it will prompt the user to "enter a number between 1 and 4."
0
 
LVL 1

Assisted Solution

by:mnadeem22
mnadeem22 earned 1000 total points
ID: 20016161
I have made certain changes to your code, by removing some logical errors and applying try-catch blocks where ever needed, now it is working properly, i have used jdk1.4, you can compile and run your program now, the modified code is given right below:

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

public class Calc
{
        //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;
         int playerChoice = 0;
         String userChoiceStr;
         String playerChoiceStr;

            //Vector v = new Vector ();
            double v[] = new double[50];

            playerChoiceStr = JOptionPane.showInputDialog(null,"How many players?");

            try
            {
                  playerChoice = Integer.parseInt(playerChoiceStr);
            }
            catch(NumberFormatException e)
            {
                  playerChoice=0;
            }

            for (i =0; i < playerChoice ; i++)
            {
                    do
                    {
                          // user input prompt
                          userChoiceStr =  JOptionPane.showInputDialog (null,

                          "Player" + " " + (i+1) + "\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

                          // switch statement to count user score

                          try
                          {
                                userChoice = Integer.parseInt(userChoiceStr);
                          }
                          catch(NumberFormatException e)
                          {
                                userChoice=4;
                          }


                          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

                  if (count !=0)
                  {
                        String str = "Got " + (result / count) + "% right!! \n";
                        v[i]= (result/count);
                        JOptionPane.showMessageDialog ( null , "You " + str );

                        String showAll = "";
                        i=0;

                        for (i =0; i < (int)playerChoice ; i++)
                        {
                              showAll = showAll + "Player "+ (i+1) + " " + 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
 

Author Comment

by:DeafBox
ID: 20018888
That doesn't work properly. First of all If i enter 2 players I want to be able to do the maths then once i press input 4 i get my score. Once i press my score it goes to the next Player, he does the maths presses input 4 and it shows his score, followed by all users scores. This is incorrect.

Also the alpha numeric checks don't work at all. Instead of looping the same input box it skips and goes to the next player.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:DeafBox
ID: 20018907
I had userChoice = Integer.parseInt(userChoiceStr); in my original code. I have no idea why it wasn't here when i posted.
0
 

Author Comment

by:DeafBox
ID: 20019509
Got most of it working except one input.


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

public class Calc
  {
  //Initialise result & count to 0

  public static int result = 0;
  public static int count = 0;
 
 
  public static void main(String[] args)
    {
       boolean inputOK = false;
       int  i=0;
       int userChoice = 0;
       double playerChoice = 0;
       String userChoiceStr ;
       String playerChoiceStr;
       
       
    //   Vector v = new Vector ();
        double v[] = new double[50];

         while (!inputOK)
        {    
            try
            {
         playerChoiceStr = JOptionPane.showInputDialog(null,
                        "How many players?");
        playerChoice = Double.parseDouble (playerChoiceStr);
         inputOK = true; // code will never reach this spot if input is not correct
        }
        catch (NumberFormatException e)
        {
           
                   
            }
        }
 
   
           
    for (i =0; i < (int)playerChoice ; i++)
    {

          do
          {          
       
              // user input prompt
              userChoiceStr =  JOptionPane.showInputDialog (null,
                             
                        "Player" + " " + (i+1)
                        + "\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
        }
    }            

    while ( userChoice != 4 );  // returns your percentage if input not equal to 4


 
String str = "Got " + (result / count) + "% right!! \n";
v[i]= (result/count);

JOptionPane.showMessageDialog ( null , "You " + str );


}

String showAll = "";
    i=0;

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

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


 
  public static void addition()
    {      
        boolean inputOK = false;
        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;
   
        while (!inputOK)
        {    
            try
            {
        selectAddition = JOptionPane.showInputDialog ("What is" + " " + genNumOne +
                                            " " + "plus" + " " + genNumTwo + "?");  
 
        additionData = Integer.parseInt(selectAddition);
        inputOK = true; // code will never reach this spot if input is not correct
        }
        catch (NumberFormatException e)
        {
                             
            }
        }
     
       if (additionData == (genNumOne + genNumTwo) )
       {
           correctAnswer() ;
           result = result + 100;
           
        }
        else
            {
        incorrectAnswer() ;
     
                                 
     }
}
 
 
    public static void subtraction()
    {    
        boolean inputOK = false;
        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
 
        while (!inputOK)
        {    
            try
            {
        selectSubtraction = JOptionPane.showInputDialog("What is" + " " + genNumOne +
                            " " + "minus" + " " + genNumTwo + "?");  
                                             
        subtractionData = Integer.parseInt(selectSubtraction);
       
         inputOK = true; // code will never reach this spot if input is not correct
        }
        catch (NumberFormatException e)
        {
                             
            }
        }
   
 
       if (subtractionData == (genNumOne - genNumTwo) )
       {
           correctAnswer() ;
           result = result + 100;
           
        }
        else
            {
        incorrectAnswer() ;
     
                                 
     }
}
     
 
 
    public static void multiplication()
    {
        boolean inputOK = false;
        int multiplicationData = 0;
        int genNumOne, genNumTwo;
        String selectMultiplication;
       
        genNumOne = (int) (Math.random() * 9) + 0;
        genNumTwo = (int) (Math.random() * 9) + 0;
 
        while (!inputOK)
        {    
            try
            {
        selectMultiplication = JOptionPane.showInputDialog("What is" + " " + genNumOne +
                                                 " " + "times" + " " + genNumTwo + "?");  
     
                                               
        multiplicationData = Integer.parseInt(selectMultiplication);
        inputOK = true; // code will never reach this spot if input is not correct
        }
        catch (NumberFormatException e)
        {
                           
            }
        }
   
 
       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
 

Author Comment

by:DeafBox
ID: 20019566
Missed out userChoice=0;

Totally working now
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
The viewer will learn how to implement Singleton Design Pattern in Java.
This video teaches viewers about errors in exception handling.
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question