Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

try-catch block  RSS feed

 
Kelvin McDoo
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys new to java and new to this forum.

This place is great for tips and help with Java.

I am currently stuck on a question I have.

The public instance method getNumOfMoves() takes no arguments and returns an integer between 1 and 3 (inclusive).
getNumOfMoves() makes use of two helper methods, promptForNumOfMoves(), which prompts the user for a number between 1 and 3 and attempts to parse the response as an integer, and isValidNumOfMoves(), which checks that the number the user has input is in the correct range 1 to 3 (inclusive). If the input is out of range, the user is prompted again, and the method continues to loop until a number in the required range is entered.
But what if the user makes a mistake and enters something that cannot be parsed as an integer at all? In this case, the parseInt() method will throw an exception and the program will simply stop executing.
To handle this case more gracefully, the promptForNumOfMoves() method can be modified to make use of a try-catch block. If an exception is thrown, the catch statement can assign 0 to the number of moves, and since this is outside the range 1 to 3 the user will be prompted to try again. (Of course any integer outside the required range could be used instead of 0 but it seems a natural choice.)
Modify the promptForNumOfMoves() method so that it handles the possible exception in the way described above.

This is what I have

*/


Any tips or help with this would be great

Thanks
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You basically described what you need to do? What is the issue that is preventing you from doing what you described?

Henry
 
Kelvin McDoo
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



This is what I have come up with
 
Zachary Griggs
Ranch Hand
Posts: 83
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, there is no return value outside of the loop, which will give you a compiler error. It's generally bad form to have exit points like that of a method anyways, so you should set moves and then set again to false, and return moves after the loop ends.
It also looks like this method can be static, since it doesn't reference any instance stuff and just returns user input (unless OUDialog is an instance of something).

Other than that, I can't see any problems. What problems are you encountering? Keep in mind we don't have the OUDialog class, so I can't comment on any of those methods referenced. I re-wrote it using a Scanner and kept the structure of your code and it works fine for me.
 
Knute Snortum
Sheriff
Posts: 4073
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One important idea when programming is the separation of concerns. This means a method should do what it "says" and only what it says. You have a method called promptFirNumOfMoves() but it also does input validation. Take out the validation code and put it into a method of its own. Pseudocode would look something like this:

 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I added code tags to your post. Always use the tags: doesn't it look better
There is an opposite approach to that shown by Knute. Move the loop out of your method, into a different method, preferably in a different class.
Stop using dialogues for input. Use a Scanner. You can write your own class so you can call int i = KeyboardInputs.nextInt("Please enter XYZ between 1 and 3: ", 1, 3}; Use one version of the method nextInt which simply returns an int, using a loop like this:-You wrap that in a method to return an int. Then you overload the method with another method of the same name but taking maximum and minimum values too. Print an error message like
"Number must be in range " + minimum + " to " + maximum
or similar.
As long as you manage to have maximum larger than minimum, that technique is another kind of separation of concerns, but it differs because:-
  • 1: The loops have been spirited away into another method in another class.
  • 2: As long as you don't have maximum ≤ minimum, you can run the whole thing without ever seeing any Exceptions
  •  
    Kelvin McDoo
    Greenhorn
    Posts: 4
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hi thanks for the replies so far

    I am getting the error missing return statment when trying to complie this




    I am trying not to use the scanner yet as we have not come across this up to now

    Thanks guys, I know this probably looks a easy fix but sometime when you spend hours looking at the same code your mind goes blank lol

     
    Knute Snortum
    Sheriff
    Posts: 4073
    112
    Chrome Eclipse IDE Java Postgres Database VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I am getting the error missing return statment when trying to complie this

    The issue is, will the method always return an int? The answer is no. What happens when the user enters an invalid number, then answers "no" to Would you like another go?

    Another issue is, why ask if the user wants another go if they enter a good number? Good formatting of your code will make this clearer.

     
    Fred Kleinschmidt
    Bartender
    Posts: 560
    9
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Kelvin McDoo wrote:To handle this case more gracefully, the promptForNumOfMoves() method can be modified to make use of a try-catch block. If an exception is thrown, the catch statement can assign 0 to the number of moves, and since this is outside the range 1 to 3 the user will be prompted to try again. (Of course any integer outside the required range could be used instead of 0 but it seems a natural choice.)


    These instructions make for poor programming. You should never return a zero (or any other number that is out of range) if the user types in something that is not a number. For example, if the caller's error message is "Your input value of 0 is not in the desired range 1-3" the user might get upset: "I didn't type a zero, I typed a three!" But she didn't realize she was holding down the Shift key when typing the 3, so it came out a # instead.

    The promptForNumberOfMoves() method should throw an exception that contains this information, and the try-catch should be in the caller of that method, not in that method itself.
     
    Kelvin McDoo
    Greenhorn
    Posts: 4
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Still have not mastered this one yet, Can anyone help and put me out of my misery?
     
    Winston Gutkowski
    Bartender
    Posts: 10573
    65
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Kelvin McDoo wrote:Thanks guys, I know this probably looks a easy fix but sometime when you spend hours looking at the same code your mind goes blank lol

    And part of the reason for that is that you do NOT solve problems by coding, so try to resist the urge to simply start bashing away at the keyboard.

    User input is surprisingly tricky - and fiddly - so you need to plan what you're going to do. And one of the ways to do that is to write down what needs to happen. For example:
    1. Prompt the user for input.
    2. Get a String.
    3. Check that the String is a valid number. If not, display a message and go back to step 1; otherwise return the resulting number.
    4. Check if the number from Step 3 is in the correct range. If not, display a message and go back to step 1; otherwise return the resulting number.
    Do you see the idea? You have TWO things that might be wrong with the input, and both of them require that your user starts over.

    Furthermore, both of those requirements (getting an integer, and getting an integer within specific limits) are things that you're likely to want to do more than once, so it might be worth designing things so that you can re-use your code.

    Since you already seem to have solved you problem, let me show you an alternative way of looking at it; and now your promptForNumOfMoves() method becomes something like:It's a fair bit more code than you wrote, but the difference is that you can now re-use those private methods for any other number you might want your user to enter, like a month or a salary or somebody's age.
    In fact, they're so useful, you might even want to put them in a separate utility class; but that's for another lesson.

    I should add that it's only one way of doing it; there are probably several others.

    The moral of the story: Don't start coding until you know what you want to do.

    HIH

    Winston
     
    Don't get me started about those stupid light bulbs.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!