2

I am actually having trouble with my program. Actually I study in school (11 grade- junior college) so please explain me in very simple language. I am developing a quiz, very basic school project and so the programs goes on like this.... I want the user to enter his/her choice, by inputting numbers from 1-4. I don't want the user to enter an alphabet, letter or special character or any other no. other than 1-4. I tried using try and catch but my program stops after throwing the exception. I want the program code to run even after displaying the error message System.out.println(" Invalid input. Please enter a number between 1-4"); sample program

import java.io.*;
  import java.lang;
  public class
  { 
   public static void main()throws IOException
   { 
     InputStreamReader read =new InputStreamReader (System.in);
     BufferedReader in =new BufferedReader (read);
     System.out.println(" Select your category");
     System.out.println(" 1. Food");
     System.out.println(" 2. National");
     System.out.println("");
     System.out.println(" Enter your choice"); 
     int choice=Integer.parseInt(in.readLine());
     if(choice==1)//food category
     { 
       int score = 0;
       System.out.println("what are dynamites made?");
       System.out.println("1. peanuts");System.out.println("2. grapes");
       System.out.println("3. flaxseeds");System.out.println("4. fish");
       System.out.println(" Enter your choice");
       int food1= Integer.parseInt(in.readline()); 
      if(c1=1)
      { System.out.println(" Correct answer");
        score=score+10
      }
       else
      { 
      System.out.println(" Wronge answer");
        score=score+0
      }
      //then i have the second question with the same format
     } 
      if(choice==2)//natioanl category with the same format as above
      {//two question with if else statements in them }
     }
}// also help me where to add the try and catch statements
leppie
  • 115,091
  • 17
  • 196
  • 297
Mahesh Sharma
  • 31
  • 1
  • 4

3 Answers3

3

The place where your program is crashing is here:

int food1= Integer.parseInt(in.readline()); 
if(c1=1)
{ System.out.println(" Correct answer");
  score=score+10
}

"c1" is not a defined variable, so use of it will cause the program to crash no matter what the user enters. You should replace "c1" with "food1". Also, the assignment operator, "=", should be replaced with the comparison operator, "==".

Check out the javadoc for Integer (google "Integer javadoc") and you will find that

public static int parseInt(String s)
                throws NumberFormatException

So NumberFormatException is what we need to catch. You can also find out what exception was thrown and where by looking at the stack trace when you run your program.

Whenever an exception is thrown, everything after the error and before the next '}' gets skipped. Since most of your code should execute fine after the error, we want to keep our try-catch small, i.e.

try {
    int choice=Integer.parseInt(in.readLine());
} catch (NumberFormatException ex) {
    //Not a number
}

We need the variable, "choice" to be accessible outside of our try, so we'll declare it outside of our try.

int choice;

try {
    choice=Integer.parseInt(in.readLine());
} catch (NumberFormatException ex) {
    //Not a number
}

However, NumberFormatException will not tell you if the user entered a number other than 1-4. So you have to add your own validation.

int choice;

try {
    choice=Integer.parseInt(in.readLine());
    if(choice<1 || choice>4) ; //Not 1-4
} catch (NumberFormatException ex) {
    //Not a number
}

Lastly, we need to keep track of whether our input is valid and loop if we need to.

boolean valid=false;

while(!valid) {

    int choice;

    try {
        choice=Integer.parseInt(in.readLine());
        if(choice<1 || choice>4) valid=false; //Not 1-4
        else valid=true;
    } catch (NumberFormatException ex) {
        //Not a number
        valid=false;
    }

    if(valid) {
         //Handle valid response here
    } else {
         System.out.println(" Invalid input. Please enter a number between 1-4");
    }
}

Good luck!

NewEndian
  • 559
  • 2
  • 16
  • Please help me... its not helping maybe I am confused about using try and catch because I am getting this error choice may have not been initialized Please post the code with try and catch in it which I can copy and paste directly or simplify with steps about using try and catch with if else statement – – Mahesh Sharma Nov 25 '12 at 10:10
  • So the warning, "choice may have not been initialized" shouldn't keep you from compiling, but the answer is simply to explicitly initialize it, i.e.: int choice=0; (You'll need to practice reading and troubleshooting errors like this) – NewEndian Nov 25 '12 at 17:22
1

Hey here is the code you can run.

import java.io.*;

import java.lang.*;

public class TestTryCatch
{ 

public static void main(String args[])
{
    try
    {
        InputStreamReader read =new InputStreamReader (System.in);
        BufferedReader in =new BufferedReader (read);
        System.out.println(" Select your category");
        System.out.println(" 1. Food");
        System.out.println(" 2. National");
        System.out.println("");
        System.out.println(" Enter your choice"); 
        int choice=0;
        try
        {
            choice =  Integer.parseInt(in.readLine());
        }
        catch(Exception e)
        {
            choice=0;
        }
        if(choice==0)
        {
            System.out.println("Invalid Input");         
        }
        if(choice==1)//food category
        { 
            int score = 0;
            System.out.println("what are dynamites made?");
            System.out.println("1. peanuts");System.out.println("2. grapes");
            System.out.println("3. flaxseeds");System.out.println("4. fish");
            System.out.println(" Enter your choice");
            int food1= Integer.parseInt(in.readLine()); 
            if(food1==1)
            { System.out.println(" Correct answer");
            score=score+10;
            }
            else
            { 
                System.out.println(" Wronge answer");
                score=score+0;
            }

        } 
        if(choice==2)
        {
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();   
    }
}
}

put a try catch where you are converting into Integer. If your code gives exception, it'll go in exception block and handle value whatever you wish. Here I have put it as 0 you can assing -1 too.

Revert back if this code is helpful or not.

akjoshi
  • 15,374
  • 13
  • 103
  • 121
Javadotnet
  • 125
  • 1
  • 1
  • 6
  • Please help me... its not helping maybe I am confused about using try and catch because I am getting this error choice may have not been initialized Please post the code with try and catch in it which I can copy and paste directly or simplify with steps about using try and catch with if else statement – Mahesh Sharma Nov 25 '12 at 09:58
  • have you copy paste comment? because I have already initalized choice. copy paste above code will run properly. I have restested too. – Javadotnet Nov 25 '12 at 20:02
0

Here's a more elegant solution to this problem. No try-catch involved.

import java.io.*;
  import java.lang;
  public class
  { 
     //Compares response to the string representations of all numbers between 1 and numOptions, inclusive. 
     //Returns the matching integer or -1 otherwise.
     public static int parseResponse(String response, int numOptions) 
     {
          for(int i=1;i<=numOptions;i++) {
              if(response.equals(Integer.toString(i))) return i;
          }
          return -1;
     }

     public static void main()throws IOException
     { 
         InputStreamReader read =new InputStreamReader (System.in);
         BufferedReader in =new BufferedReader (read);
         System.out.println(" Select your category");
         System.out.println(" 1. Food");
         System.out.println(" 2. National");
         System.out.println("");
         System.out.println(" Enter your choice");

         //New code
         int choice=-1;
         while(choice==-1) {
             choice=parseResponse(in.readLine(),2);
             if(choice==-1)
             {
                 System.out.println(" Invalid input. Please enter a number between 1-2");
             }
         }


         if(choice==1)//food category
         { 
             int score = 0;
             System.out.println("what are dynamites made?");
             System.out.println("1. peanuts");System.out.println("2. grapes");
             System.out.println("3. flaxseeds");System.out.println("4. fish");
             System.out.println(" Enter your choice");

             //New code
             int food1=-1;
             while(food1==-1) {
                 food1=parseResponse(in.readLine(),4);
                 if(food1==-1)
                 {
                     System.out.println(" Invalid input. Please enter a number between 1-4");
                 }
             }

             if(food1==1)
             { System.out.println(" Correct answer");
               score=score+10
             }
             else
             { 
               System.out.println(" Wronge answer");
               score=score+0
             }
             //then i have the second question with the same format
        } 
        if(choice==2)//natioanl category with the same format as above
        {//two question with if else statements in them 
        }
    }
}// also help me where to add the try and catch statements

In case you don't know:

 if(response.equals(Integer.toString(i))) return i;

is the same as

 if(response.equals(Integer.toString(i)))
 {
      return i;
 }
NewEndian
  • 559
  • 2
  • 16