Reputation: 1
I recently started programming with java and need help.
Using Programming Java for Dummies, I'm trying to make a game where a user has to guess a number. The amount of attempts are recorded and displayed once the user finally gets the answer right.
The starred line is giving me trouble, any help?
import static java.lang.System.out;
import java.util.Scanner;
import java.util.Random;
import javax.swing.JOptionPane;
public class HelloWorld
{
public static void main(String args[])
{
Scanner keyboard = new Scanner (System.in);
out.println("Hello, welcome to the Guessing Game.");
out.println("To begin, pick a random number from 1 - 10: ");
int inputNumber = keyboard.nextInt();
int randomNumber = new Random(1).nextInt(10);
int numGuesses = 0;
while (inputNumber != randomNumber){
out.println();
out.println("You're guess was wrong, try again.");
out.println("Pick an integer from 1-10.");
**int inputNumber = keyboard.nextInt();**
numGuesses++;
}
{
out.println("You won in " + numGuesses + " guesses.");
out.println("Thanks for playing!");
}
}
}
Upvotes: 0
Views: 848
Reputation: 2429
You already defined at the top so you dont have to redefine it. Instead it should be inputNumber = keyboard.nextInt();
Upvotes: 0
Reputation: 31952
Replace
**int inputNumber = keyboard.nextInt();**
with
inputNumber = keyboard.nextInt();
With the original version, you are creating a new variable within the scope of the while
, rather than assign to the old variable outside.
Since it is destroyed after the while block, the condition itself uses the variable in functions scope.
Upvotes: 6
Reputation: 8125
This line is redeclaring inputNumber, which has already been declared.
int inputNumber = keyboard.nextInt();
change it to
inputNumber = keyboard.nextInt();
Upvotes: 3