3 Replies - 458 Views - Last Post: 29 April 2013 - 09:02 PM Rate Topic: -----

#1 Bayonetwork   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 27-April 13

Returning/looping a try catch block

Posted 29 April 2013 - 11:04 AM

I am trying to error catch this segment of code. I want to make sure user enters an integer that is > 0.
Also, if no input is given then it should System.exit().

Here is my attempt that will catch a non integer input and print "Error" but it wont as for number of disks again.


try {
		System.out.print("\nHow many disks should we use for Hanoi problem: ");
		input = keyboard.nextLine();
		n = Integer.valueOf(input);
		} catch (NumberFormatException nfe) {
			System.out.println("Error: Invalid Input.");
		}
		
			int userInput = keyboard.nextInt();
			while (userInput <= 0) {  
			        System.out.print("Invalid! Input must be greater than 0.");
			}
		


Is This A Good Question/Topic? 0
  • +

Replies To: Returning/looping a try catch block

#2 Michael26   User is offline

  • Futurama: Insert funny joke here
  • member icon

Reputation: 414
  • View blog
  • Posts: 1,664
  • Joined: 08-April 09

Re: Returning/looping a try catch block

Posted 29 April 2013 - 11:15 AM

You need to check the input if it's > 0, something like

if(input < 0) 
        // print the error message


Was This Post Helpful? 0
  • +
  • -

#3 Bayonetwork   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 27-April 13

Re: Returning/looping a try catch block

Posted 29 April 2013 - 11:23 AM

View PostMichael26, on 29 April 2013 - 11:15 AM, said:

You need to check the input if it's > 0, something like

if(input < 0) 
        // print the error message



Where would I check it? I want to loop through the try catch block until they enter an integer. If they do enter an integer and it is <0 then it should loop through my while loop until it is finally an integer > 0.
Was This Post Helpful? 0
  • +
  • -

#4 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Returning/looping a try catch block

Posted 29 April 2013 - 09:02 PM

for something like that use a while(true) and break out of it when good results
Also limit the try/cath to the code that can generate the exception, a lot eaiser to read... or, while you are at it, put all your code inside try/catch blocks :)
   int n = 0;
   while(true) {
	System.out.print("\nHow many disks should we use for Hanoi problem: ");
	input = keyboard.nextLine();
        try {
	    n = Integer.valueOf(input);
	} catch (NumberFormatException nfe) {
	    System.out.println("Error: Invalid Input.");
	    continue;
	}
		
	if(n <= 0) {  
	     System.out.print("Invalid! Input must be greater than 0.");
             continue;
	}
        break;
    }


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1