-1

I have a project to create a program that picks a number (1-10), then has the user guess. If they are too high it tells them so and same goes for if they guessed too low. Now to mistake-proof it, I have to add try and catch blocks. If you look at the code you will see that I have but when triggered the code processes the catch then finishes. How do I get it to loop back?

    import java.util.*;
    import java.lang.*;

    class GuessDR {

        public static void main(String[] args){



            System.out.println("Welcome to my number guessing game!");

            int maxnum = 10;
            Scanner input = new Scanner(System.in);
            Random rand = new Random();
            int number = rand.nextInt(maxnum);
            int tries = 0;         
            int guess;
            boolean win = false;

             try{

               while (win == false){ 



                   System.out.println("Guess a number between 1 and "+                     
                   maxnum +": ");
                   guess = input.nextInt();
                   tries++;    
                   if (guess == number){
                       win = true; 
                   }

                   else if(guess < number){
                       System.out.println("Number is to low, tray again");

                   }

                   else if(guess > number){
                       System.out.println("Number is to high, try again");

                   }

               }
            }

            catch (InputMismatchException e) {

                System.out.println("Enter numerical guess");            

            }
     System.out.println("You win!");
     System.out.println("It took you "+ tries + " tries.");

    }
 }
Aburito
  • 5
  • 3
  • Try moving the try-catch block inside the while loop. – AJNeufeld Dec 05 '17 at 21:58
  • Easy way? Move the `try` and `catch` bits into the loop. :P – cHao Dec 05 '17 at 21:58
  • In anticipation of your next question (new guesses keep generating a `InputMismatchException`), see [this question & answer](https://stackoverflow.com/questions/29811339/cannot-figure-out-how-to-catch-inputmismatchexception) – AJNeufeld Dec 05 '17 at 22:09

2 Answers2

1

Just move try-catch into the while loop and also provide proper input.nextLine() method inside your catch block to clear invalid input from the buffer:

   import java.util.*;
   import java.lang.*;

    class GuessDR {

        public static void main(String[] args) {

            System.out.println("Welcome to my number guessing game!");

            int maxnum = 10;

            Random rand = new Random();
            int number = rand.nextInt(maxnum);
            int tries = 0;
            int guess;
            boolean win = false;
            Scanner input = new Scanner(System.in);

            while (win == false) {
                try {

                    System.out.println("Guess a number between 1 and " + maxnum + ": ");
                    guess = input.nextInt();
                    tries++;
                    if (guess == number) {
                        win = true;
                    }

                    else if (guess < number) {
                        System.out.println("Number is to low, tray again");

                    }

                    else if (guess > number) {
                        System.out.println("Number is to high, try again");

                    }

                } catch (InputMismatchException e) {
                    input.nextLine();
                    System.out.println("Enter numerical guess");

                }
            }

            System.out.println("You win!");
            System.out.println("It took you " + tries + " tries.");

        }
    }
Przemysław Moskal
  • 3,321
  • 2
  • 8
  • 20
  • Oh, my code seems to be ok - I just forgot to mention about moving Scanner into the while loop to prevent infinite loop. On my way to make appropriate edit. – Przemysław Moskal Dec 05 '17 at 22:12
  • I must have done something a tad different than you. I had originally tried doing that. However, it created an infinite loop. Copy over your code and it works fine. – Aburito Dec 05 '17 at 22:13
  • If you think that my answer is correct you might consider upvoting it and tick it on the left side to accept it. – Przemysław Moskal Dec 05 '17 at 22:15
  • What is the reason of the downvote? Let me know what's wrong with it to make me edit it properly – Przemysław Moskal Dec 05 '17 at 22:18
  • 1
    This is a poor solution - you should create the `Scanner` only once, not each iteration of the `while` loop. The `Scanner` will read and internally buffer the standard-input stream. Discarding the scanner and recreating it may result in missing input stream data. (Not usually noticable for keyboard input, but if you read input from a file, or redirect standard input, you can observe this.) Instead, create the `Scanner` once, outside the loop, and use `scanner.nextLine()` to clear out invalid input in the `catch` clause. – AJNeufeld Dec 05 '17 at 22:19
  • Ok, I'll try to edit my answer and hope you reconsider a downvote. – Przemysław Moskal Dec 05 '17 at 22:21
  • Thank you for providing me an explanation, it's good to know that and it will help me in using Scanner in the future for sure. I hope I made an edit meeting your expectations because I find it a bit hard to check that code on the mobile device. – Przemysław Moskal Dec 05 '17 at 22:46
0

Move try-catch into the while loop and handle the scanner to prevenet infinite loop. Check it out: https://stackoverflow.com/a/3572233/5964489

while (win == false)
        {

            System.out.println("Guess a number between 1 and "
                    + maxnum + ": ");
            try
            {
                guess = input.nextInt();
                tries++;
                if (guess == number)
                {
                    win = true;
                } else if (guess < number)
                {
                    System.out.println("Number is to low, tray again");

                } else if (guess > number)
                {
                    System.out.println("Number is to high, try again");

                }

            } catch (InputMismatchException e)
            {
                System.out.println("Enter numerical guess");
                input.next();
            }
        }
Emre Sülün
  • 541
  • 8
  • 19