Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Mar 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    GuessingGame - help with code

    Hi all,

    New to this forum, and new to Java. I'm trying to create a guessing game where the user is required to guess a number between 1 to 100. The game provides feedback to the user if the guess is higher or lower. When the user does guess the number, they are given a message with the total number of attempts.

    When I run this code, I get an error on the last line that 'guess cannot be resolved'. Any help would be appreciated.


    import java.util.Scanner;

    public class GuessingGame2
    {
    public static void main (String[] args)
    {
    int tries = 0;

    double randomNum = (int)(Math.random() * 100 + 1);
    int num = (int)(randomNum + 1);
    System.out.print(num);

    do
    {
    System.out.print("Please enter a number between 1 and 100: ");
    Scanner numGuessString = new Scanner(System.in);
    int guess = numGuessString.nextInt();

    tries++;


    if(guess>num)
    {
    System.out.println("Too high. Try again.");
    System.out.println();
    }
    if(guess<num)
    {
    System.out.println("Too low. Try again.");
    System.out.println();
    }
    if(guess==num)
    {
    System.out.println("Correct! It took you " + tries + " tries to guess the number!");
    }

    } while (guess!=num) ;
    }
    }

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,652
    Thanks
    80
    Thanked 4,640 Times in 4,602 Posts
    You need to learn about SCOPE in Java.

    Your variable
    Code:
        int guess = numGuessString.nextInt();
    is declared *inside* the do {... } block. So it is only accessible inside that block.

    You don't need to move the assignment. You only need to move the declaration.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •