try/catch in do while loop

Not working as expected

Page 1 of 1

7 Replies - 33176 Views - Last Post: 04 November 2008 - 04:03 PM Rate Topic: -----

#1 Itxi   User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 25
  • Joined: 03-November 08

try/catch in do while loop

Post icon  Posted 03 November 2008 - 11:47 AM

Hello :)
as part of my coursework I have to make a program that calculates the area of a triangle of sides input by the user. Part of this code is checking that the values entered are correct, which is what the following method is for. It will pick up on negative values and ask for the user to re-enter a positive number.

However the try/catch to ask the user to re-enter input if a letter was entered by mistake just leaves the program hanging. Please can anyone point out what mistake I have made?
public static double enterValue()
	{
		Scanner scanner = new Scanner(System.in);
		boolean wrong = true;
		double a = 0;
		do
		{
			try
			{
				a = scanner.nextDouble();
				if (a >0)
				{
					wrong = false;
				}
				else
				{
					System.out.print("Please enter positive values only: ");
				}
			}
			catch (InputMismatchException e)
			{
				System.out.print("Please enter numerical values only: ");
			}
		} while (wrong);
		return a;
	}



Many thanks ;)

Is This A Good Question/Topic? 0
  • +

Replies To: try/catch in do while loop

#2 stauffski   User is offline

  • D.I.C Head

Reputation: 27
  • View blog
  • Posts: 216
  • Joined: 03-November 07

Re: try/catch in do while loop

Posted 03 November 2008 - 02:25 PM

You are using a try-catch statement improperly. the statements are meant to be used when using prewritten classes that might throw an exception. First, you would need to have a throw line, which you don't do. So, since there is nothing to be thrown, it will never catch. Writing throw statements is good practice when writing classes for other classes. But this is all internal so therefore you would know what went wrong. The purpose of the statement is to inform the external classes what went wrong in your class.

So, what you should do, is just write a simple if statement that determines whether or not you need to reloop. I have provided what I think is most practical.

public static double enterValue(){
   Scanner scanner = new Scanner(System.in);
   boolean valid = true;
   double value = 0;
   
   do{
      if(valid){
         System.out.print("Please enter a value: ");
      }
      else{
         System.out.print("Please enter positive values only: ");
      }
      value = scanner.nextDouble();

      if (value < 0){
         valid= false;
      }
   }while (!valid);

   return value;
}



That should do it for you. If you have any questions feel free to ask.

Good Luck!
Was This Post Helpful? 1
  • +
  • -

#3 DaneAU   User is offline

  • Great::Southern::Land
  • member icon

Reputation: 286
  • View blog
  • Posts: 1,620
  • Joined: 15-May 08

Re: try/catch in do while loop

Posted 03 November 2008 - 03:16 PM

Are you doing this to prevent IOExceptions such as intering a char or string instead of an integer(double)....

import java.util.*;
import java.io.*;

class Catch
{
	Scanner scanner = new Scanner(System.in);
	double a = 0;
	
	
	public double enterValue() throws InputMismatchException
    {
        boolean wrong = true;
        try {        
	        do
	        {
	    		System.out.println("Enter Positive Value");
	            a = scanner.nextDouble();
	            if (a > 0)
	            {
	                wrong = false;
	            }
	            else
	            {
	                System.out.print("Please enter positive values only: ");
	            }            
	            
	        } while (wrong);
	        
        } catch(InputMismatchException e)	{}
        
        return a;
    }
    
    
    public static void main(String[] args) throws IOException	
    {
    	Catch myCatch = new Catch();
    	myCatch.enterValue();    	
    }
}


This post has been edited by bbq: 03 November 2008 - 03:31 PM

Was This Post Helpful? 1
  • +
  • -

#4 pbl   User is offline

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

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

Re: try/catch in do while loop

Posted 03 November 2008 - 09:02 PM

View Poststauffski, on 3 Nov, 2008 - 01:25 PM, said:

You are using a try-catch statement improperly. the statements are meant to be used when using prewritten classes that might throw an exception.


Sorry Stauffski you are wrong
That is exactly what the scanner class does... throwng an execption
So this code seems OK to me.

May be Scanner can throw something else... so

replace your catch(InputMismatchException e)

by

catch(Exception e) {
System.out.println("Exception is: " + e);
}

and let's see what happend
Was This Post Helpful? 1
  • +
  • -

#5 Itxi   User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 25
  • Joined: 03-November 08

Re: try/catch in do while loop

Posted 04 November 2008 - 03:08 PM

stauffski, cheers for the advice, I have not tried your code yet though it does not ask for the user to re-enter values if they are not numeric, which is what I am aiming for. However I have used try/catch like this before and it has worked.

pbl, I changed the code to:
catch (Exception e)
			{
					System.out.println(e);
				System.out.print("Please enter numerical values only: ");
			}


and I got a continuous loop of :
Please enter numerical values only: java.util.InputMismatchException
Even though I thought it would print out the exception first :blink:

If I leave it as just
 catch (Exception e)
			{
								System.out.print("Please enter numerical values only: ");
			}


The program still hangs.

bbq, thankyou but before I try it please can you explain exactly what it is that code does? I'm not too good at interpreting code yet :)

This post has been edited by Itxi: 04 November 2008 - 03:10 PM

Was This Post Helpful? 0
  • +
  • -

#6 stauffski   User is offline

  • D.I.C Head

Reputation: 27
  • View blog
  • Posts: 216
  • Joined: 03-November 07

Re: try/catch in do while loop

Posted 04 November 2008 - 03:36 PM

Ohhhhhhhhhh, my bad. I thought that you thought the Scanner would throw if it was a negative number. Gotcha.

So now that everything is clear, this is what I have come up with.

import java.util.*;

public class EnterValue{
    public static double enterValue(){
        Scanner scanner = new Scanner(System.in);
        boolean valid = true;
        double a = 0;
        
        do{
            try{
                if (a >= 0 && valid){
                    System.out.print("Please enter a positive value: ");
                }
                else if(valid){
                    System.out.print("Please enter positive values only: ");
                }
                a = scanner.nextDouble();
                valid = true;
            }
            catch (InputMismatchException e){
                System.out.print("Please enter numerical values only: ");
                scanner = new Scanner(System.in);
                valid = false;
            }
        }while (!valid || a < 0);
        
        return a;
    }
}



That should do it for ya. If you have any questions as to what is going on in the code, just ask.

Good Luck!
Was This Post Helpful? 1
  • +
  • -

#7 Itxi   User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 25
  • Joined: 03-November 08

Re: try/catch in do while loop

Posted 04 November 2008 - 03:44 PM

Perfect! Thankyou very much :)
Was This Post Helpful? 0
  • +
  • -

#8 DaneAU   User is offline

  • Great::Southern::Land
  • member icon

Reputation: 286
  • View blog
  • Posts: 1,620
  • Joined: 15-May 08

Re: try/catch in do while loop

Posted 04 November 2008 - 04:03 PM

Basically it executes the main method and creates an instance of the class and then executes the enterValue method.

It will

do the loop while values are wrong as you say and catch an input error for instance entering a non integer value such as 'a'... the program will quit but the error messages won't come up. You have to work out ways of handling IO exceptions etc...
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1