Reputation: 19
this is my code and I have a do-while loop which should carry on unless the string "text" entered is "stop". However when I compile the code it doesnt stop and stuck in an infinite loop. Pease help. Thanks.
import java.io.*;
public class input
{
public static void main(String[] argv) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String text = "";
do
{
System.out.println("Please enter a string: ");
text = br.readLine();
System.out.println(text);
}
while (text != "stop");
}
}
Upvotes: 0
Views: 16525
Reputation: 24630
All posters are right: you should use String.equals().
Also you should complete understand String handling in Java. You will need it everywhere.
Even that String.equals should be used Java offers some "magic", that works even with your comparison. Keep learning !
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String text = "";
"stop".intern();
do {
System.out.println("Please enter a string: ");
text = br.readLine().intern();
System.out.println(text);
} while (text != "stop");
}
Upvotes: 0
Reputation: 28693
You cannot compare strings using ==
. Use equals
: while(!"stop".equals(text))
.
Also since it comes from the user input, you might want to compare ignoring the case, you can use equalsIgnoreCase
.
Upvotes: 0
Reputation: 64632
Replace
while (text != "stop")
with
while (!text.equals("stop"))
Upvotes: 0
Reputation: 206786
You are comparing strings with !=
. That does not work in Java. You should use equals()
to compare strings:
while (!text.equals("stop"));
Note that ==
and !=
on objects compare the references - i.e., if you use those operators on non-primitive variables, you are checking if the variables refer to the same object, and not if the content of those objects is the same.
Upvotes: 0
Reputation: 9255
Try replacing text != "stop"
by !text.equals("stop")
!=
is a reference equality test, .equals()
is a logical equality test. Two strings can be different objects and still be logicaly equals (same content in this case).
Upvotes: 2