I am learning from a book to code with java. It gives an example of a guessing game and gives the code. I wanted to keep it as a reference. But I keep getting an error. And it might be the way I typed it cause I am reading it off a kindle and it kinda got a little messed up.
There are many errors like this, but none like mine. I am trying to make a guessing game, but I keep getting this error:
GuessingGame.java:17: not a statement (int)(Math.random() * 10) + 1;
Code:
import java.util.Scanner;
public class GuessingGame
{
static Scanner sc = new
Scanner(System.in);
public static void
main(String[] args)
{
bolean keepPlaying = true;
System.out.println("Let's play a guessing game!");
while (keepplaying)
{
bolean validInput;
int number, guess;
String answer;
// Pick a random number =
(int)(Math.random() * 10) + 1;
// Get the guess
System.out.print("What do you think it is? ");
do
{
guess = sc.nextInt();
validInput = true;
if ((guess < 1) || (guess > 10))
{
System.out.print
("I said between 1 and 10. "
+ "Try again: ");
validInput = false;
}
}while (!validInput);
// Check the guess
if (guess == number)
System.out.println(
"You're right!");
else
System.out.println(
"You're wrong! " + "The number was " + number);
// Play again?
do
{
System.out.println("\nPlay again? (Yes or No)");
answer = sc.next();
validInput = true;
if (asnwer.equalsIgnoreCase("Yes"));
else if (answer.egualsIgnoreCase("No")-
keepPlaying = false);
else
validInput = false;
} while (!validInput);
}
System.out.println("\nThank you for playing!");
}
}
It's true, (int)(Math.random() * 10) + 1;
isn't a statement. And Java, unlike some other langauges, doesn't allow just expressions as statements.
I think the word number
in the comment above belongs on the line:
Not:
// Pick a random number =
(int)(Math.random() * 10) + 1;
But:
// Pick a random number
number = (int)(Math.random() * 10) + 1;
(There's already an int number;
above, so the variable is already declared and everything.)
You need to assign the value you are computing in the statement to a variable. IN your case it is the variable number.
number = (int)(Math.random() * 10) + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With