1

i need help for generating of unlimited strings from keyboard, but this don't work..

Scanner input = new Scanner(System.in);
    ArrayList<String> al = new ArrayList<String>();

     String check=null;
      while(true){
          check = input.nextLine();
          if(check == "stop") break;
          al.add(check);

      }
      System.out.println(al);
}

}

  • 1
    `unlimited`? and `doesn't work`? I don't understand what you're trying to do or what problem you're having, but.... `if(check == "stop")` is almost definitely not doing what you want it to do. – nhgrif Oct 25 '13 at 16:22

2 Answers2

4
if(check == "stop")

This is wrong and should instead be written as:

if("stop".equals(check))
nhgrif
  • 61,578
  • 25
  • 134
  • 173
2

To compare objects in java use .equals() method instead of "==" operator

Need to change

if(check == "stop") break;

to

if("stop".equals(check)) break;
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • 2
    While your answer is not wrong, it is my understand that `"stop".equals(check)` is slightly better because `check` could be null. – nhgrif Oct 25 '13 at 16:24
  • Np. :/ Except now your answer has more votes than mine. :( Haha. – nhgrif Oct 25 '13 at 16:28
  • 1
    If you're not worried about null then for fun you could also write it like this: `if (check.intern() == "stop")` By "for fun" I mean, "to drive your coworkers crazy" :) Seriously, though, if you understand how `intern()` works then you'll have a good understanding of how Strings work in Java, or at least why `==` doesn't always work but sometimes does. – Paul Oct 25 '13 at 16:43