-2

When I create a variable and wrap the code in a while loop it never repeats. Here's a sample of code I tried it on.

String repeat = "y";
    Scanner keyboard = new Scanner(System.in);
    while (repeat == "y"){
        String word1 = "this";
        String word2 = "that";
        String word3 = word1 + word2;
        System.out.println(word3);
        for(int x = 10; x<20; x = x+1){

            word3 = word1 + word3;
            System.out.println(word3);
        }
        repeat = keyboard.nextLine();
    }

No matter what the input is in the end of the script, it just ends. Any help?

durron597
  • 31,968
  • 17
  • 99
  • 158
rvogel
  • 83
  • 1
  • 1
  • 9
  • 9
    Use `String`'s `equals` method to compare `String` values, not `==`, which compares object references to determine if they refer to the same object. – rgettman Sep 06 '13 at 17:47
  • @rgettman They are literals here though, unless there's something missing in the code. – Sotirios Delimanolis Sep 06 '13 at 17:48
  • @SotiriosDelimanolis Yes, they are literals, so `"y"` will be interned. The `while` loop will be entered for that reason. But after `repeat = keyboard.nextLine();`, then `repeat` won't be a literal any more. Either way, `.equals` is needed here. – rgettman Sep 06 '13 at 17:50
  • @rgettman Right, it'll fail the next time. I stopped thinking :) – Sotirios Delimanolis Sep 06 '13 at 17:50

4 Answers4

1

Change the line

 while (repeat == "y")

to

while("y".equalsIngnoreCase(repeat))  

and

keyboard.nextLine() ; 

to

keyboard.next();  

Reading How do I compare strings in Java? will be helpful.

Community
  • 1
  • 1
Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
0

When you compare a string using '=='. you are comparing the object reference. You are essentially asking if the two objects are the same, rather than comparing the string contents. Try using the String.compareTo(..) method.

Example:

while (repeat.compareTo("y") == 0) {
samsquanch
  • 521
  • 3
  • 12
0

The problem probably comes from the facts you compare two objects with = but I guess what you want to do is compare Strings with the String method equals, so it would look like that:

while(repeat.equals("y")){
...
}
Barbe Rouge
  • 394
  • 1
  • 6
  • 18
0

Never use == to compare strings.

Try this:-

  while ("y".equalsIngnoreCase(repeat) )
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331