Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-23-2010, 06:43 PM   PM User | #1
abbasrizvi
New to the CF scene

 
Join Date: Mar 2010
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
abbasrizvi is an unknown quantity at this point
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) ;
}
}
abbasrizvi is offline   Reply With Quote
Old 03-23-2010, 07:52 PM   PM User | #2
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,249
Thanks: 59
Thanked 3,999 Times in 3,968 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 08:24 AM.


Advertisement
Log in to turn off these ads.