Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 18 of 18

Thread: Cant seem to get my loop to work after catching an exception.

  1. #1
    Junior Member
    Join Date
    Jul 2014
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Cant seem to get my loop to work after catching an exception.

    Sorry about that here's the edit:

    I am trying to get user inputs (double types). so when i get a letter instead of a double i get an exception even though i had a while loop checking for this. so i looked up how to do exception handling and now when i get to that point it catches it but only outputs the message i gave and terminates instead of going through the while loop again. apparently there is no way to go back to before the error happened unless you use a while loop. but the loop isn't working it just terminates.

    here's the code:

    public static void collectInfo()
    	{
     
    	double firstW=0;
    	double secondW=0;
    	double payRate =0;
    	double holiHours =0;
    	boolean firstWGood = true;	 
    	boolean secondWGood = true;
    	boolean payRateGood = true;
    	boolean holiHoursGood = true;
     
    		Scanner in = new Scanner (System.in);
    		do{
    			try{
    			System.out.println("Enter hours received for the first week of your paycheck. ");
    			System.out.println("If you have overtime, just add it to this for example: 3 hours of overtime is 43 hours that week");
     
    		firstW = in.nextDouble();
    		firstWGood = false;
    } catch (InputMismatchException e){
    	System.out.println("Oops...");
     
    }	
    		}while(!firstWGood);


    and here's the output when i ran the program(console):

    Enter hours received for the first week of your paycheck.
    If you have overtime, just add it to this for example: 3 hours of overtime is 43 hours that week
    h
    Oops...
    Last edited by lonnieg1214; July 3rd, 2014 at 08:46 PM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE GOES HERE
    [/code]
    to get highlighting and preserve formatting.

    instead of going through the while loop again.
    What would keep the loop executing? What is the value of the variable need to be? What is its value when the loop starts? The code doesn't show it.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jul 2014
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    Sorry i'm new to all of this.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    The while() loop will continue to execute as long as the expression inside of the loop has a true value.
    What was the value of the expression in the while loop when it executed? For the loop to exit it must be false.

    What value of firstWGood will allow the loop to exit?
    What value of firstWGood will keep the loop looping?

    What was the value of firstWGood when the loop started executing?

    Do you know what the ! operator does with a boolean value?

    What happens when a good value is entered and there is no exception?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jul 2014
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    Quote Originally Posted by Norm View Post
    The while() loop will continue to execute as long as the expression inside of the loop has a true value.
    What was the value of the expression in the while loop when it executed? For the loop to exit it must be false.

    What value of firstWGood will allow the loop to exit?
    What value of firstWGood will keep the loop looping?

    What was the value of firstWGood when the loop started executing?

    Do you know what the ! operator does with a boolean value?

    What happens when a good value is entered and there is no exception?
    The way that the code is setup now it won't loop at all I wanted it to loop back to give the user another chance to put in the right info.
    The ! Should make it false right? And since firstWGood started with true, that should make it loop back right?

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    If firstWord is true, then !firstWord is false, and the do/while loop will end. The sample run you posted confirmed that.

    Don't question the results, question the logic that provided the results.

  7. #7
    Junior Member
    Join Date
    Jul 2014
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    Quote Originally Posted by GregBrannon View Post
    If firstWord is true, then !firstWord is false, and the do/while loop will end. The sample run you posted confirmed that.

    Don't question the results, question the logic that provided the results.
    Ahh ok I keep getting confused on the loop so I start off with it being true and I want it to remain true if the user puts in the right info. But when they cause an exception, I changed the true to false to match the while condition so it would loop over. I have also tried it another way but it keeps looping over and over in an infinite loop. It seems to keep the entry that the user provided instead of getting rid of it and really starting over. How can I get the system to forget the entry and just retry the same portion. I have seen examples of just starting the whole thing over but I don't want to do that if the user is on the last entry and has to start over.

    I think I have an idea when it catches the exception maybe I could have it default to a number like -1 and have the loop condition to repeat if it's less than 0?

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    But when they cause an exception, I changed the true to false to match the while condition so it would loop over.
    You can use the catch{} block to achieve this. Your code indenting is also funky, causing the code to be harder to read:
    do
    {
        // reset the repeat flag
        firstWGood = true;
     
        try
        {
            System.out.println("Enter hours received for the first week of your paycheck. ");
            System.out.println("If you have overtime, just add it to this for example: 3 hours of overtime is 43 hours that week");
     
            firstW = in.nextDouble();
        }
        catch (InputMismatchException e)
        {
            // the entry was improper, so try again
            firstWGood = false;
            System.out.println("Oops...");
     
        }
     
    }while(!firstWGood);
    With this design, you can adjust the true/false flag name and value to be more intuitive - or maybe you're happy with the way they are.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    when they cause an exception, I changed the true to false
    Look at the code. Does it do that?

    EDIT: Looks like Greg has fixed it for you.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Jul 2014
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    i tried what Greg did just now but it goes into an eternal loop

    --- Update ---

    right before i tried Greg's solution, i tried restarting the method when the exception occurred. that worked but that would suck for the user if they get to the fourth question and enter a letter on accident and then they will have to start all over again.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    goes into an eternal loop
    Can you copy the first part of the console showing what was entered and what the code printed out?

    Read the API doc for the nextDouble() method to see what it does:
    when there is good data
    when there is bad data

    Hint: the bad data is left in the buffer.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Jul 2014
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    Enter hours received for the first week of your paycheck.
    If you have overtime, just add it to this for example: 3 hours of overtime is 43 hours that week
    h
    Oops...

    this is how it would go but then it will keep outputting this:

    Enter hours received for the first week of your paycheck.
    If you have overtime, just add it to this for example: 3 hours of overtime is 43 hours that week
    Oops...
    Enter hours received for the first week of your paycheck.
    If you have overtime, just add it to this for example: 3 hours of overtime is 43 hours that week
    Oops...

  13. #13
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    Post your updated loop or method - enough to see the changes you made.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    Did you read and understand the rest of my post#11?
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Junior Member
    Join Date
    Jul 2014
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    is it possible to override anything to get the response i want? maybe overriding the error so it doesn't keep the bad data? that explains why it keeps looping

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    so it doesn't keep the bad data
    You can use another Scanner class method to read the bad data from the Scanner's buffer.
    For debugging you should also print out a message showing the bad data that was read.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Junior Member
    Join Date
    Jul 2014
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    here is what i changed it to which works but isn't ideal from a user's standpoint:
    public static void collectInfo()
    	{
     
    	double firstW=0;
    	double secondW=0;
    	double payRate =0;
    	double holiHours =0;
    	boolean firstWGood = true;	 
    	boolean secondWGood = true;
    	boolean payRateGood = true;
    	boolean holiHoursGood = true;
     
    		Scanner in = new Scanner (System.in);
     
    			try{
    			System.out.println("Enter hours received for the first week of your paycheck. ");
    			System.out.println("If you have overtime, just add it to this for example: 3 hours of overtime is 43 hours that week");
     
    		firstW = in.nextDouble();
     
    } catch (InputMismatchException e)
    {
    	UserInputs.collectInfo();
    	System.out.println("Oops...");	
    }	
     
     
    }


    --- Update ---

    here's what i read but i don't see where it talks about the buffer but i did hear about the buffer you spoke about from stack overflow

    nextDouble
    public double 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.
    If the next token matches the Float regular expression defined above then the token is converted into a double value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Double.parseDouble. If the token matches the localized NaN or infinity strings, then either "Nan" or "Infinity" is passed to Double.parseDouble as appropriate.

    Returns:
    the double scanned from the input
    Throws:
    InputMismatchException - if the next token does not match the Float regular expression, or is out of range
    NoSuchElementException - if the input is exhausted
    IllegalStateException - if this scanner is closed

    --- Update ---



    I think i got it based on your guys advice here's what i came up with:

    do
    		{
     
    			System.out.println("Enter hours received for the first week of your paycheck. ");
    			System.out.println("If you have overtime, just add it to this for example: 3 hours of overtime is 43 hours that week");
    try
    {
    		firstW = in.nextDouble();
     
    			break;
     
    } catch (InputMismatchException e)
    {
    	//UserInputs.collectInfo();
    	in.next();
    	System.out.println("oops... you may want to try to enter a number");	
    }
    		}
    		while(!in.hasNextDouble());
     
     
    }


    let me know what you think also this is a static method that i was working on was that a good idea to implement?

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Cant seem to get my loop to work after catching an exception.

    If the translation is successful, the scanner advances past the input that matched.
    From that I assume that if the translation is NOT successful, the scanner does NOT advance, ie it leaves the bad data in the buffer.

    I used buffer in the generic sense referring to a place in the class where it reads data entered by the user (or from a file) and then scans over it as the program requests parts of it via the different Scanner class methods.

    Using a recursive call is not the way to handle the problem. A loop with some variables should handle it.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Help with getting a loop to work
    By keyrock in forum Loops & Control Statements
    Replies: 3
    Last Post: October 26th, 2013, 10:01 PM
  2. Replies: 2
    Last Post: June 20th, 2013, 10:02 PM
  3. Can't get the loop to work properly
    By thegreatzo in forum What's Wrong With My Code?
    Replies: 2
    Last Post: August 9th, 2012, 02:57 PM
  4. [SOLVED] Problems with Try/Catch Catching Wrong Exception
    By bgroenks96 in forum What's Wrong With My Code?
    Replies: 14
    Last Post: June 10th, 2011, 08:08 PM
  5. Quick question with throwing and catching an exception.
    By Andyandhisboard in forum What's Wrong With My Code?
    Replies: 6
    Last Post: May 12th, 2011, 10:24 PM