5 Replies - 3973 Views - Last Post: 25 April 2007 - 08:46 PM Rate Topic: -----

#1 ClintWB  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 02-September 06

Help with Try/Catch and While statement

Posted 30 September 2006 - 07:34 PM

try/catch while statement seems to work but has a few little quirks it asks for input twice ("Enter the multiplication table you wish to practice: ") not really sure why and if you put in good int and then a bad on the second it has number format error and won't catch it. If someone could help with this I'm taking a distance learning class and the book really just doesn't seem to explain it very well.
I'm not sure if the statement is even correct the book says to enclose with the calling user defined methods. Thanks for any help provided.


import java.io.*;

public class Multiply
{
  public static void main (String[] args ) throws IOException
  {
	//Declaring variables
	int multiplier;
	int correct;
	boolean done = false;

	//Opening messages
	System.out.println("\t\tWelcome to the Multiplication Quiz");
	System.out.println("");

	while (!done)
 	{
 	try
		  {multiplier = getNumber();
		  done=true;
 		 }

 	catch (NumberFormatException e)
 		{
 			System.out.println("Incorrect number format try again!");
 		}


	}
	 //Calling the user-defined methods
	multiplier = getNumber();
	correct = takeQuiz(multiplier);
	System.out.println("\t\tYou got "+correct+ " correct!" );

  }


   public static int getNumber() throws IOException
   {
	  //Declaring variables
	  BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
	  String inputData;
	  int multiplier;

	  //Get a value from user
	  System.out.print("Enter the multiplication table you wish to practice: ");
		 inputData = dataIn.readLine();
		 multiplier = Integer.parseInt( inputData );

	  //Return a value to main
	  return multiplier;
   }

   public static int takeQuiz(int multiplier) throws IOException
   {
	 //Declaring variables
	  BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
	  String inputData;
	  int answer;
	  int count = 0;
	  int correct = 0;

	  while ( count <= 12)
	  {
		 //Display question and get answer
		 System.out.println( "What is "+count + " times " + multiplier +"?" );
			inputData = dataIn.readLine();
			answer	 = Integer.parseInt( inputData );

		 if (answer == count * multiplier)
		 {
			System.out.println("\tCorrect!");
			correct = correct + 1;
		 }

		 else
		 {
		   	System.out.println("\tIncorrect");
		 }

		 count = count + 1;
	  }
	  return correct;
   }
}





Is This A Good Question/Topic? 0
  • +

Replies To: Help with Try/Catch and While statement

#2 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Help with Try/Catch and While statement

Posted 30 September 2006 - 08:24 PM

You want to catch the error at the source, rather than after completion of you method. Otherwise you won't effectively catch the problem. So rather than having the try/catch in your main, you want to have it where your are actually getting the input from the user. In essence you want the try/catch inside your getNumber and takeQuiz methods.

As for the problem with duplicate questions that is because of how you are utilizing your while loop. Basically what is happening is your varable done is set to true after the first time your method executes. This causes you to exit the while loop immediatly where you have a second call to your method, hence the second question. At this point you execute your takeQuiz method.

The solution is you need to have an IF statement to determine when it is time to set your boolean to true. But unfortunately you have not given the user a sentinal value that they can type in that will cause your program to terminate. You need a sentinal value in order to create a condition by which you can terminate your program. In this case, since you are working with numbers that will always be positive (I am assuming anyway), then -1 makes an excellent sentinal value. But you can make it any integer value that you would like, so long as you let the user know what that value is in order to exit your program.

Last thing, you need System.exit(0); in your program so that your application can close properly.

Other than that very nicely done.

Now I have modified your code with the changes I described. Hopefully I didn't overexplain everthing.
import java.io.*;

public class Multiply
{
  public static void main (String[] args ) throws IOException
  {
	//Declaring variables
	int multiplier;
	int correct;
	boolean done = false;

	//Opening messages
	System.out.println("\t\tWelcome to the Multiplication Quiz");
	System.out.println("");

	while (!done)
	{
		  multiplier = getNumber();
		  
		  if (multiplier == -1)
		  {
			done=true;
		}
		else
		{	  
			//Calling the user-defined methods
			correct = takeQuiz(multiplier);
			System.out.println("\t\tYou got "+correct+ " correct!" );  
		}
	}

	System.exit(0);
  }


   public static int getNumber() throws IOException
   {
	  //Declaring variables
	  BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
	  String inputData;
	  int multiplier = 0;
	try
	{	
	
	  //Get a value from user
	  System.out.print("Enter the multiplication table you wish to practice(-1 to quite): ");
	  inputData = dataIn.readLine();
	  multiplier = Integer.parseInt( inputData );
	}
	
	catch (NumberFormatException e)
	{
		System.out.println("Incorrect number format try again!");
	}

	  //Return a value to main
	  return multiplier;
   }

   public static int takeQuiz(int multiplier) throws IOException
   {
	 //Declaring variables
	  BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
	  String inputData;
	  int answer;
	  int count = 0;
	  int correct = 0;

	  
		  try
		  {
			  while ( count <= 12)
			  {
		  
		 		//Display question and get answer
		 		System.out.println( "What is "+count + " times " + multiplier +"?" );
				inputData = dataIn.readLine();
				answer	 = Integer.parseInt( inputData );

		 		if (answer == count * multiplier)
		 		{
					System.out.println("\tCorrect!");
					correct = correct + 1;
		 		}

		 		else
		 		{
			   		System.out.println("\tIncorrect");
		 		}

		 		count = count + 1;
				  }
		  }
		  
		  catch(NumberFormatException e)
		  {
			  System.out.println("Incorrect number format try again!");
		  }
		  
	  return correct;
   }
}


Was This Post Helpful? 0
  • +
  • -

#3 ClintWB  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 02-September 06

Re: Help with Try/Catch and While statement

Posted 30 September 2006 - 10:30 PM

View Postjayman9, on 30 Sep, 2006 - 08:24 PM, said:

You want to catch the error at the source, rather than after completion of you method. Otherwise you won't effectively catch the problem. So rather than having the try/catch in your main, you want to have it where your are actually getting the input from the user. In essence you want the try/catch inside your getNumber and takeQuiz methods.

As for the problem with duplicate questions that is because of how you are utilizing your while loop. Basically what is happening is your varable done is set to true after the first time your method executes. This causes you to exit the while loop immediatly where you have a second call to your method, hence the second question. At this point you execute your takeQuiz method.

The solution is you need to have an IF statement to determine when it is time to set your boolean to true. But unfortunately you have not given the user a sentinal value that they can type in that will cause your program to terminate. You need a sentinal value in order to create a condition by which you can terminate your program. In this case, since you are working with numbers that will always be positive (I am assuming anyway), then -1 makes an excellent sentinal value. But you can make it any integer value that you would like, so long as you let the user know what that value is in order to exit your program.

Last thing, you need System.exit(0); in your program so that your application can close properly.

Other than that very nicely done.

Now I have modified your code with the changes I described. Hopefully I didn't overexplain everthing.
import java.io.*;

public class Multiply
{
  public static void main (String[] args ) throws IOException
  {
	//Declaring variables
	int multiplier;
	int correct;
	boolean done = false;

	//Opening messages
	System.out.println("\t\tWelcome to the Multiplication Quiz");
	System.out.println("");

	while (!done)
	{
		  multiplier = getNumber();
		  
		  if (multiplier == -1)
		  {
			done=true;
		}
		else
		{	  
			//Calling the user-defined methods
			correct = takeQuiz(multiplier);
			System.out.println("\t\tYou got "+correct+ " correct!" );  
		}
	}

	System.exit(0);
  }


   public static int getNumber() throws IOException
   {
	  //Declaring variables
	  BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
	  String inputData;
	  int multiplier = 0;
	try
	{	
	
	  //Get a value from user
	  System.out.print("Enter the multiplication table you wish to practice(-1 to quite): ");
	  inputData = dataIn.readLine();
	  multiplier = Integer.parseInt( inputData );
	}
	
	catch (NumberFormatException e)
	{
		System.out.println("Incorrect number format try again!");
	}

	  //Return a value to main
	  return multiplier;
   }

   public static int takeQuiz(int multiplier) throws IOException
   {
	 //Declaring variables
	  BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
	  String inputData;
	  int answer;
	  int count = 0;
	  int correct = 0;

	  
		  try
		  {
			  while ( count <= 12)
			  {
		  
		 		//Display question and get answer
		 		System.out.println( "What is "+count + " times " + multiplier +"?" );
				inputData = dataIn.readLine();
				answer	 = Integer.parseInt( inputData );

		 		if (answer == count * multiplier)
		 		{
					System.out.println("\tCorrect!");
					correct = correct + 1;
		 		}

		 		else
		 		{
			   		System.out.println("\tIncorrect");
		 		}

		 		count = count + 1;
				  }
		  }
		  
		  catch(NumberFormatException e)
		  {
			  System.out.println("Incorrect number format try again!");
		  }
		  
	  return correct;
   }
}



Thanks for the help I'm still messing with the code and I thought the try statement should of been placed in the method too...not sure why the book wanted it in the main is it possible to use the try statement in the main method using a different statement just wondering, with the code change you have made the only question I have is when a non int is used it defaults to zero how would it return to ask for another input after exception.

again thanks this has been one of the tougher classes in programming I've had!
Was This Post Helpful? 0
  • +
  • -

#4 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Help with Try/Catch and While statement

Posted 01 October 2006 - 09:36 AM

You can solve that problem by adding another IF statement to your while loop and enclosing the previous code inside. Since you know that if incorrect input is entered the value stored in multiplier is equal to 0. That will be the test condition of the IF statement. Basically if the input is 0 bypass all the rest of the code and restart your WHILE loop.
Was This Post Helpful? 0
  • +
  • -

#5 dbrine  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 52
  • Joined: 25-April 07

Re: Help with Try/Catch and While statement

Posted 25 April 2007 - 07:20 PM

Where is the throw NumberFormatException in the try statement? I don't understand what the catch statement caught if it's not in the try??




View PostClintWB, on 30 Sep, 2006 - 07:34 PM, said:

try/catch while statement seems to work but has a few little quirks it asks for input twice ("Enter the multiplication table you wish to practice: ") not really sure why and if you put in good int and then a bad on the second it has number format error and won't catch it. If someone could help with this I'm taking a distance learning class and the book really just doesn't seem to explain it very well.
I'm not sure if the statement is even correct the book says to enclose with the calling user defined methods. Thanks for any help provided.


import java.io.*;

public class Multiply
{
  public static void main (String[] args ) throws IOException
  {
	//Declaring variables
	int multiplier;
	int correct;
	boolean done = false;

	//Opening messages
	System.out.println("\t\tWelcome to the Multiplication Quiz");
	System.out.println("");

	while (!done)
 	{
 	try
		  {multiplier = getNumber();
		  done=true;
 		 }

 	catch (NumberFormatException e)
 		{
 			System.out.println("Incorrect number format try again!");
 		}


	}
	 //Calling the user-defined methods
	multiplier = getNumber();
	correct = takeQuiz(multiplier);
	System.out.println("\t\tYou got "+correct+ " correct!" );

  }


   public static int getNumber() throws IOException
   {
	  //Declaring variables
	  BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
	  String inputData;
	  int multiplier;

	  //Get a value from user
	  System.out.print("Enter the multiplication table you wish to practice: ");
		 inputData = dataIn.readLine();
		 multiplier = Integer.parseInt( inputData );

	  //Return a value to main
	  return multiplier;
   }

   public static int takeQuiz(int multiplier) throws IOException
   {
	 //Declaring variables
	  BufferedReader dataIn = new BufferedReader (new InputStreamReader(System.in));
	  String inputData;
	  int answer;
	  int count = 0;
	  int correct = 0;

	  while ( count <= 12)
	  {
		 //Display question and get answer
		 System.out.println( "What is "+count + " times " + multiplier +"?" );
			inputData = dataIn.readLine();
			answer	 = Integer.parseInt( inputData );

		 if (answer == count * multiplier)
		 {
			System.out.println("\tCorrect!");
			correct = correct + 1;
		 }

		 else
		 {
		   	System.out.println("\tIncorrect");
		 }

		 count = count + 1;
	  }
	  return correct;
   }
}




Was This Post Helpful? 0
  • +
  • -

#6 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Help with Try/Catch and While statement

Posted 25 April 2007 - 08:46 PM

What makes you think that the throw NumberFormatException must be inside the the Try/Catch block?

There is no such requirement.

Did you not see the main method declaration?
public static void main (String[] args ) throws IOException

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1