-3

Noob Java question: Why won't this Do While loop accept the user input? When I use a different variation (such as int for the answer), it works. But when I look for a string, it never accepts the string and escapes the loop.

This works:

int value = 0;
do {
    System.out.println("Enter a number: ");
    value = scanner.nextInt();
}
while(value != 5);
System.out.println("Do while loop has ended.");

This doesn't work:

String pass;
String word = "word";
do {
    System.out.println("Enter password: ");
    pass = scanner.nextLine();
}
while(pass != word);
System.out.println("Password accepted.");

Thanks

Wouter J
  • 41,455
  • 15
  • 107
  • 112
Jawa
  • 99
  • 2
  • 12
  • 1
    you should be using string.equals() method. the way you are comparing is their memory location not the literal string. – madteapot Apr 10 '14 at 15:53

2 Answers2

3

Change this:

while(pass != word);

to this:

while(!pass.equals(word));

You were comparing the references when you used !=, not the actual content of the strings. Since they did not point to the same String, your loop would always exit on the first run.

Azar
  • 1,086
  • 12
  • 27
0

"==" compares addresses in memory so if you enter the word which will be the same, the reference you have stored will point to different object.

Lucas
  • 3,181
  • 4
  • 26
  • 45