I'm trying to create a program in which the user thinks of a number between 1 and 10, and the computer repeatedly tries to guess it by guessing random numbers. (It's ok to guess the same number more than once) At the end of the game, the program reports how many guesses it made. For example:
I have written the following code:
import java.util.*;
public class Pick {
public static void main(String[] args){
System.out.println("This program has you, the user, choose a number");
System.out.println("between 1 and 10. Then, I, the computer, will try");
System.out.println("my best to guess it.");
Scanner console = new Scanner(System.in);
Random r = new Random();
int result = -1;
int count = 0;
for (i = 1; i <= number; i++){
while(result != number){
result = r.nextInt(10) + 1;
System.out.println("Is it " + r + "? (y/n)");
String yn = console.next();
if(String yn = "y"){
System.out.println("I got your number of " + result + " in " + i + " guesses.");
} else if (String yn = "n") {
count++;
} else {
System.out.println("I got your number of " + result + " in " + i + " guesses.");
}
}
System.out.println();
}
}
I'm confused as to why my program doesn't work? It won't compile and has 7 errors. I think I went wrong in the if/else statements. Should I have used a while loop? Thanks.
compilation errors by text:
Pick.java:20: error: ')' expected
if(String yn = "y"){
^
Pick.java:20: error: ';' expected
if(String yn = "y"){
^
Pick.java:22: error: ')' expected
} else if (String yn = "n") {
^
Pick.java:22: error: ';' expected
} else if (String yn = "n") {
^
Pick.java:22: error: 'else' without 'if'
} else if (String yn = "n") {
^
Pick.java:25: error: 'else' without 'if'
} else {
^
Pick.java:31: error: reached end of file while parsing
}
^
7 errors