I am learning JAVA and trying to write my first loop. The loop should prompt the user to guess a defined name.
The code is not performing right. I have tried to search for help on different JAVA tuturials both not found any examples where you guess a name/string but a lot where you should guess a number.
This is my code:
/**
*
* @author mso_
*/
import java.util.Scanner;
public class GuessName {
/**
* @param args the command line arguments
*/
public static final int C_Max_Trials = 10;
public static void main(String[] args) {
//Define correct name
String name = "Morten";
String guessName;
//Create a scanner
Scanner guess = new Scanner(System.in);
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
String guessName = guess.next(); <-- ERROR
//Create loop
} while (guessName != name); <-- ERROR
System.out.println("Sorry, wrong guess, please enter another guess: ");
if (guessName = name); <-- ERROR
System.out.println("Right on! ");
}
}
What have I done wrong?
String comparison
You can’t compare Strings like this. This will only compare the references. You must use the equals() method :
A little explanation : http://www.zparacha.com/java-string-comparison/
Variable redeclaration
There is another error in your code, you try to redeclare guessName inside the loop. You must declare guessName only once outside of the loop (ie before the
do {).General mistakes
Thirdly, there’s a some other errors in your code. I think all of them were pointed out in the others answer, but I’ll do a quick list :
if (guessName = name);This is a useless statement as is, you must open a block :if(condition) { statement; }System.out.println()won’t be executed when you think. Re-read the doc about do { } while() loop until you really understand them.My advise : read carefully the error message of your compiler and read some doc before writing code.