Results 1 to 4 of 4
Like Tree1Likes
  • 1 Post By pbrockway2

Thread: Stuck in continuous loop with try/catch block

  1. #1
    ndsmith20 is offline Member
    Join Date
    Oct 2012
    Posts
    55
    Rep Power
    0

    Default Stuck in continuous loop with try/catch block

    Hi, I need to create a try/catch blocks for the scanner class and be able to continue entering in more info after the exception is caught, here is what i have:
    Circle Class
    Java Code:
    public class Circle{
    	
    	String msg = "Radius of circle must be greater than 0";
        private double radius;    // the radius of the circle
    
        /**
         * Constructor - Create a new circle.
         *
         * @param    inRadius  radius of the circle
    	  *throw illegal argument exception if inRadius less than or equal to 0
         */
    
        public Circle(double inRadius ) {
    		try
    		{
            if (inRadius <= 0.0)
    		  {
    		  	throw new ShapeException(msg);
    		  }
    		}
    		catch(ShapeException e)
    		{
    			
    		}
    		  radius = inRadius;
    		  
        }
    
        /**
         * Return the radius of the circle.
         *
         * @return    radius of the circle
         */
    
        public double getRadius() {
    		return radius;
        }
    
        /**
         * set the radius
         * @param newRadius		new radius of the circle
    	  *throw exception if newRadius less than or equal to 0
         */
    
        public void setRadius(double newRadius) {
    		 try
    		{
            if (newRadius <= 0.0)
    		  {
    		  	throw new ShapeException(msg);
    		  }
    		}
    		catch(ShapeException e)
    		{
    			System.out.println("Radius must be greater than 0");
    			System.exit(0);
    		}
    
    		radius = newRadius;
    	}
    
        /**
         * Compute and return the area of the circle.
         *
         * @return    the area of the circle
         */
    
        public double area() {
    		return Math.PI * radius * radius;
        }
    
        /**
         * Stretches the size of the circle by multiplying
         * the radius by the factor provided.
         *
         * @param    factor    factor to stretch by
         *
         */
    
        public void stretchBy(double factor ) {
    
            try
    		{
            if (factor <= 0.0)
    		  {
    		  	throw new ShapeException(msg);
    		  }
    		}
    		catch(ShapeException e)
    		{
    			System.out.println("Factor must be greater than 0");
    			System.exit(0);
    		}
    
    		  radius = radius * factor;
    
        }
    
        /**
         * Return a string representation of a circle.
         *
         * @return    a string representing this circle
         */
    
        public String toString() {
    
           // implement body here
    		 return "Circle: "+radius;
    
        }
    
    } // Circle
    Shape Exception Class
    Java Code:
    public class ShapeException extends Exception 
    {
       
       public ShapeException(String message) 
       {
          super(message);
       }
    }
    Test Class
    Java Code:
    import java.util.*;
    
    public class TestCircleC {
       public static void main(String [] args) {
    	  
    	  String msg = "Shape Exception occured";
    	  double radius = 0;
    	  Scanner scan = new Scanner(System.in);
    	  //System.out.print("Enter a circle radius: ");
    	  boolean loop = true;
    	 while(loop != false)
    	 {
    	 //System.out.print("Enter a circle radius: ");
    	 try
    	  {
    	  	System.out.print("Enter a circle radius: ");
    	  	radius =scan.nextDouble();
    		 // Instantiate a Circle object
          Circle aCircle = new Circle(radius);
    		// Print current status of the circle
          System.out.println(aCircle);
    
    	  	if(radius <= 0.0)
    		{
    			throw new ShapeException(msg);
    		}
    	  }
    	  catch (ShapeException e)
    	  {
    	  	System.out.println("Shape Exception occured...");
    	  }
    	  catch(InputMismatchException e)
    	  {
    	  	System.out.println("InputMismatchException occurred...");
    	  }
    	  catch(NoSuchElementException e)
    	  {
    	  	System.out.println("CTRL+C Program stops...");
    		loop = false;
    		System.exit(0);
    		
    	  }
    	}
      }
    }
    My results:
    Enter a circle radius: 12
    Circle: 12.0
    Enter a circle radius: -12
    Circle: -12.0
    Shape Exception occured...
    Enter a circle radius: fo
    InputMismatchException occurred...
    Enter a circle radius: InputMismatchException occurred...
    Enter a circle radius: InputMismatchException occurred...
    Enter a circle radius: InputMismatchException occurred...
    Enter a circle radius: InputMismatchException occurred.

    please help, I dont know why it is doing this

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,573
    Rep Power
    12

    Default Re: Stuck in continuous loop with try/catch block

    radius =scan.nextDouble();
    According to the API documentation nextDouble() "Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched".

    The important thing is that the method moves past the input that matched. If there is no input that matches (eg because the user entered "fo") then the scanner will not advance. So, in your case, the scanner sees "fo" and throws the exception, then another prompt is written and the scanner (which is still looking at "fo") will throw the exception again. And the whole process repeats itself for ever.

    There is, therefore, a very important difference between nextDouble() and friends (nextInt() etc) and nextLine(). nextLine() always "consumes" its input and moves on to the next line while the others don't move at all if there is an exception.

    This is a very common gotcha when people use Scanner for input and there are a couple of things you could explore to get the code to move on even when there is an exception:

    (1) If you expect the value to be the only thing that the user enters before pushing the <enter> key, then you could use nextLine() rather than nextDouble(). This will return you a String rather than a double. You can get the corresponding double value by calling Double.parseDouble(). parseDouble() can also throw an exception (and will throw one if the string is "fo") which you could catch and report. But at least when you go round the loop the second time the scanner will return the next line of input the user enters and not keep seeing "fo" and throwing the exception.

    (2) In the catch block for the InputMismatchException you could call the nextLine() method and do nothing at all with the String it returns. This will "consume" the string "fo" and anything that occurs on the line after it leaving you ready to receive more user input.

    In terms of how much change is needed to your existing code (2) involves less work. There is also a hasNextDouble() method in the scanner class which tells you if there is a double ready to be read rather than your program finding out about it via an exception.
    Last edited by pbrockway2; 02-02-2013 at 03:49 AM.
    ndsmith20 likes this.

  3. #3
    ndsmith20 is offline Member
    Join Date
    Oct 2012
    Posts
    55
    Rep Power
    0

    Default Re: Stuck in continuous loop with try/catch block

    pbrock, I went with option 2 and it worked. Thank you so much!!!

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,573
    Rep Power
    12

    Default Re: Stuck in continuous loop with try/catch block

    You're welcome.

Similar Threads

  1. Try Catch Block
    By Jackbower in forum New To Java
    Replies: 3
    Last Post: 05-06-2012, 08:00 AM
  2. Try/catch block
    By swati.jyoti in forum New To Java
    Replies: 5
    Last Post: 07-02-2009, 03:32 PM
  3. Question reg try/catch block
    By nn12 in forum New To Java
    Replies: 1
    Last Post: 09-16-2008, 06:56 PM
  4. Try Catch block issues
    By kewlgeye in forum New To Java
    Replies: 11
    Last Post: 04-29-2008, 08:10 AM
  5. try...catch block
    By javaplus in forum New To Java
    Replies: 3
    Last Post: 11-06-2007, 08:53 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •