-2

Create a program that randomly generates a number from 1-100 and asks the user to guess it. If the number the user inputs is to low or to high display a message to tell them so. When the user guesses the random number tell the user how much tries it took him to get that number. After that ask the user if they want to do it again if the user does repeat the process with a new random number generated.

The problem is that I can't seem to figure out how to let the user do it again, it seems to display an error in code when I run the program. If anyone can help me with this issue that would be great. Thank you!

import java.util.Scanner;
import java.util.Random;
public class RandomGuess
{
    public static void main(String [] args)
    {
        Scanner keyboard = new Scanner(System.in);
        Random randy = new Random();

        //#declaring variables
        int num, count = 0;
        final int random = randy.nextInt(100);
        String input;
        char yn;

        //#random number
        System.out.println("Num = " + random);

        //#title or header
        System.out.println("Random Number Guessing Game");
        System.out.println("===========================");

        //#asking user for input
        do
        {
            System.out.print("Guess the random number " + 
                "from 1 to 100===> ");
            num = keyboard.nextInt();

            //#if the number the user entered
            //#was less than the random number
            if(num < random)
            {
                //#display this message
                System.out.println("Your guess is too low try again...");
                System.out.println();
            }
            //#if the number the user entered
            //#was less than the random number
            if(num > random)
            {
                //#display this message
                System.out.println("Your guess is too high try again...");
                System.out.println();
            }
            count++;
            if (num == random)
            {
                System.out.println("You guessed the random number in " + 
                    count + " guesses!");
                break;
            }
            do 
            {
                System.out.print("Continue? (Y or N)==> ");
                input = keyboard.nextLine();
                yn = input.charAt(0);
            }
            while(yn == 'Y' || yn == 'y');
        }
        while (num > 1 || num > 100);

    }
}
  • What error does it display? – GBlodgett May 15 '19 at 22:07
  • Can you post what the error is? – GMc May 15 '19 at 22:09
  • It displays the error whenever I enter the first number for the first question the error shows: java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47) at java.base/java.lang.String.charAt(String.java:693) at RandomGuess.main(RandomGuess.java:57) – Cubix Cube May 15 '19 at 22:11
  • Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – GBlodgett May 15 '19 at 22:12

1 Answers1

0

There are a couple of problems with your code without even seeing the error that is displayed (I've put comments in those areas):

            count++;
            if (num == random)
            {
                System.out.println("You guessed the random number in " + 
                    count + " guesses!");
                break;
            }   // You should put an else here
            do 
            {
                System.out.print("Continue? (Y or N)==> ");
                input = keyboard.nextLine();
                yn = input.charAt(0);
            }
            while(yn == 'Y' || yn == 'y');  // This will keep asking if you want to try again so long as you enter a "y"
                     // But it won't actually let you try.
                     // Why? Because if you enter a y" it will loop back to the question.   
        }
        while (num > 1 || num > 100); // This should probably be (random != num)

    }
}

Here is a revised version

            count++;
            if (num == random) {
                System.out.println("You guessed the random number in " + 
                    count + " guesses!");
            } else {
                yn = 'x';    // can be anything other than y or n
                while(yn != 'y' && yn != 'n') {
                  System.out.print("Continue? (Y or N)==> ");
                  input = keyboard.nextLine();
                  yn = input.toLowerCase().charAt(0);
                }
            }
        }
        while (num != random && yn == 'y');
    }
}

Hopefully this is enough to move you forward.

Also, please post the error message and/or a description of what it is doing wrong along with a description as to what you actually wnt it to do.

As for the exception, the problem is that scanner.nextInt does not consume the newline at the end of the numbe you entered. So, your "continue Y/N" question gets what's left over from the previous line (i.e. a new line => an empty string).

You could try this:

    num = -1;       // Initialise the number to enable the loop
    while (num <= 1 || num >= 100) {
      System.out.print("Guess the random number from 1 to 100===> ");
      String ans = keyboard.nextline();
      try {
        num = Integer.parseInt();     // Convert the string to an integer - if possible
      } catch (NumberFormatException e) {
           // If the user's input can not be converted to an integer, we will end up here and display an error message.
        System.out.println ("Please enter an integer");
      }
    }
GMc
  • 1,614
  • 1
  • 6
  • 24
  • I've added some detail that should address your exception. If this has helped you can you please accept the answer by clicking the grey check mark next to the answer. Thanks. – GMc May 15 '19 at 22:40
  • I think you kind of misinterpreted what I meant to do so if the user entered a number less than 1 or greater than 100 the program would display a message that they entered invalid input, and also when I ran the program every time I entered a number it would display a error so I changed it to .next(); after I only entered one number it asked the user if they wanted to continue and repeats every time it works but what I'm trying to do is first for the user to enter numbers until they have guessed the random number and then ask them if they want to continue. – Cubix Cube May 16 '19 at 00:48
  • It is possible, that I have misintepreted your goal (which is why it is important to post your goal), but right now, assuming you do not get the Exception (which hopefully the last part of my answer will address), your program will behave as follows: 1) Enter a number 2) Check for correctness (it will exit if correct otherwise it will say too high or too low). Assume not correct, it will ask "Try again Y/N?". It will keep asking that question until you answer "Y" or "Yes" There is no test for "n" which will be treated the same as if the user entered "OK" or "X" or anything else. – GMc May 16 '19 at 02:34
  • Finally, it will loop if the number entered is > 1 (or > 100) so effectively it will loop if any positive number is entered. It would exit is a -ve number or 0 was entered. The other parts of my answer address some of these behaviors which do not seem quite right. So step 1 address the exception with the last part of my answer and try some of the inputs I mention, then consider the first parts of my answer and see if they help with other parts of your project. Feel free to omit them if they do not help. – GMc May 16 '19 at 02:38
  • If you want to modify the prompt to play again only after the number is guessed (or maybe a the limit of guesses is reached) then you will need the "Play again" loop to be the outer loop and the read guess, check high /low to be the inside the "Play again" loop. Right now, you've got the "Play again" loop inside the number guessing loop. To achieve your goal, you will need to "invert" your loops. – GMc May 16 '19 at 02:45
  • If this has helped you, can you please accept the answer and upvote? Thanks – GMc May 22 '19 at 05:50