Cbin
Cbin

Reputation: 13

Java While Loop

Why doesn't my loop end when I enter "Done"?

    List<String> x = new ArrayList<String>();
    BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    String line = "";

    while (line != "Done")
    {
        System.out.println("?> ");
        line = is.readLine();
        x.add(line);

    }

Upvotes: 1

Views: 1350

Answers (6)

user5226747
user5226747

Reputation: 33

You can't compare two strings using !=

You'll have to use equals() method.

while (!line.equals("Done"))

Upvotes: 0

Rasel
Rasel

Reputation: 15477

while (!line.equals("Done")) {
    System.out.println("?> ");
    line = is.readLine();
    x.add(line);
}

Upvotes: 1

paulsm4
paulsm4

Reputation: 121869

Try this:

import java.io.*;
import java.util.*;

class Tmp
{
  public static void main (String[] args) throws IOException
  {
    List<String> x = new ArrayList<String>();
    BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    String line = "";

    while (line.compareTo ("Done") != 0)
    {
        System.out.print("?> ");
        line = is.readLine();
        x.add(line);
        System.out.println ("IO: " + line + "..."); 
    }
  }
}

The issue is that "==" compares the object reference of the string constant "Done" to the reference to the other string object "line". Since they're two different objects, their references are never equal.

Instead, you need to COMPARE the value "Done" to the value of "line".

'Hope that helps!

PS: When I saw this question, there were no replies.

It never takes me any less than 10-15 minutes to formulate and test a reply.

By which time multiple other replies inevitably squeeze in.

I don't do "fast" ;)

But I try my best for "accurate" ;)

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234857

Replace this:

while (line != "Done")

with this:

while (!line.equals("Done"))

You can't compare two strings for lexical inequality using !=; that only tests whether they are different objects.

Upvotes: 2

Daniel
Daniel

Reputation: 3057

You'll have to use equals(), == identity does not work with Strings as you might expect.

Upvotes: 1

wjans
wjans

Reputation: 10115

You have to use equals when comparing strings. Try this:

while(!"Done".equals(line))

!= will check the reference, not the content of the string.

Upvotes: 6

Related Questions