0

I am relatively new to Java and all programming in general. I'm writing a simple GuessNumber program for school. The user enters a number 1-10 and it is compared to a random number 1-10. The req spec states that all invalid input should be checked and the user should be re-prompted if invalid input is found. I am using try-catch-finally for this. My catch block finds the exception for int guess if it is indeed not an integer, but it does not re-prompt the user, and instead keeps the initial value of 0. I only initialized guess before user input because the terminal repeatedly yelled at me about it until I did. I am also not sure why the variable must be initialized before the try block.

I looked all over but every solution I've found has code nearly identical to mine in structure. I'm guessing this must be something that I simply am not familiar with/others neglect to mention because it is so elementary. This is my first time using try-catch-finally by the way.

int guess = 0;
int number = (int)((Math.random()*10) + 1);
System.out.print("Please guess a number between 1 and 10, inclusive: ");

//open try
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

  guess = Integer.parseInt(br.readLine());

  //monitor input
  while(guess < 1 || guess > 10) {//open while

    System.out.print("You seem to have entered something wrong. Please only");
    System.out.println(" enter ");
    System.out.print("an integer number between 1 and 10, 1 and 10 included: ");
    guess = Integer.parseInt(br.readLine());

  }//close while

  //close try
} catch(NumberFormatException e) {//open catch

  System.out.print("You seem to have entered something wrong.  Please only");
  System.out.println(" enter ");
  System.out.print("an integer number between 1 and 10, 1 and 10 included: ");

  //close catch
} finally {//open finally

  //user feedback
  if(number == guess){

    System.out.println("You got it! You guessed the number correctly. It is "
    + number + ".");

  } else {

    System.out.println("I'm sorry! That is not the number I was thinking of.");
    System.out.println("You guessed " + guess + ", but the number is "
    + number + ".");

  }
}//close finally

If the user enters an exclamation point ! for example, the program does out put the catch block code. However, it then moves on with 0 as the guess and runs the rest of the program, and ends. The program works correctly if an integer is entered, however. Any input is greatly appreciated!

EDIT: I deleted the finally block, and threw the try-catch blocks inside a while loop with a boolean variable boolean done = false; with the condition while(!done) if the try is successful, it sets done = true; and the program ends. That wasn't good enough and I had infinite looping from exceptions, so I threw some continue; statements at the end of the catch blocks and that worked. Can anyone explain why the continue statements were necessary/how they affect the flow of the program?

    //init vars needed
    int guess;
    int number = (int)((Math.random()*10) + 1);
    boolean done = false;
    System.out.print("Please guess a number between 1 and 10, inclusive: ");

    while(!done) {//open while
      try {//open try
        guess = Integer.parseInt(br.readLine());

        while(guess < 1 || guess > 10) {
          System.out.print("You seem to have entered something wrong. Please only");
          System.out.println(" enter ");
          System.out.print("an integer number between 1 and 10, 1 and 10 included: ");
          guess = Integer.parseInt(br.readLine());
        }

        if(number == guess) {
          System.out.println("You got it! You guessed the number correctly. It is "
          + number + ".");
        } else if(number != guess) {
          System.out.println("I'm sorry! That is not the number I was thinking of.");
          System.out.println("You guessed " + guess + ", but the number is "
          + number + ".");
        }

        done = true;
      } //close try

      catch(NumberFormatException e) {//open catch
        System.out.print("You seem to have entered something wrong. Please only");
        System.out.println(" enter ");
        System.out.print("an integer number between 1 and 10, 1 and 10 included: ");
        continue;
      }//close catch

      catch(IOException e) {//open catch
        System.out.print("You seem to have entered something wrong. Please only");
        System.out.println(" enter ");
        System.out.print("an integer number between 1 and 10, 1 and 10 included: ");
        continue;
      }//close catch

    }//close while

3 Answers3

3

An exception thrown from parseInt causes your loop to break. You probably want your loop to contain a try-catch-finally clause, and not vice-versa.

Shloim
  • 5,281
  • 21
  • 36
  • That word "break" got me thinking and I threw it all into a while loop, like you said and added some continue statements at the end of the catch blocks. Please refer to the original post edited, and please let me know if you know why the continue statement is necessary and how it really affects the flow of the loop – Austin Abbate Oct 22 '19 at 13:17
  • Sorry, I just did it. It's edited at the end of the original post now. I'm new to this platform so I didn't know if adding a second block of code would be informal/against the rules. – Austin Abbate Oct 22 '19 at 14:16
  • I don't see a reason why the `continue` statement is necessary. Try to debug your program to see the differences. If you do not succeed then maybe you should post it as a separate question. – Shloim Oct 22 '19 at 21:22
  • I simply removed them and it all just worked... maybe I was just missing a brace before or something. Thanks a lot for your help – Austin Abbate Oct 25 '19 at 15:25
2

You should organize your code, first as other coments said you should execute your code in try and handle the exceptions on the catch, finally is redundant if you are going to execute in the try block. Use this as an example, you also have another question where they can explain better than me. Hope it helped. [link] Does a finally block always get executed in Java?

    try {
        System.out.println("Im the try block");
    }
    finally {
        System.out.println("Im the finally block");
    }

Output:

Im the finally block 
Im the try block

Also NumberformatException is going to work when you put a number but you missed the IOException I think.

ICodeForCaffeine
  • 195
  • 2
  • 10
  • I'm going to have to read up on exception types... thanks for your input, I added a second catch block to catch IOExceptions. – Austin Abbate Oct 22 '19 at 13:15
1

Finally section will happen anyway, regardless of exception or not. you should put the code from the finally section in the try section.

eyalka
  • 21
  • 5