-1

I want user to input text while it is not equal to "start".When it is equal to "start" I want to show "Bravo".In my code when I enter "start" it just continue to ask to input a text.What is missing in my code to process the operation i described.

import java.util.Scanner;

public class Application {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String komanda = "a";
    do { 
        System.out.println("Unesi komandu ");
        komanda = input.nextLine();
    }
    while(komanda != "start");
    System.out.println("Bravo");
  }
}
Danstahr
  • 4,190
  • 22
  • 38
Dusan
  • 47
  • 1
  • 1
  • 7
  • if I only see one more "java strings compare" question,I will throw my cat out of the window. – SteveL Sep 06 '14 at 16:50

2 Answers2

1

You have to use the equals method to compare strings in java:

while (!komanda.equals("start"));

or even better

while (!"start".equals(komanda));

this does not crash if komanda is null

See How do I compare strings in Java? for more information.

MrTux
  • 32,350
  • 30
  • 109
  • 146
  • +1 for recommending literal on left hand side. – Adam Sep 06 '14 at 16:26
  • @Adam `komanda` cannot possibly be `null` and the Yoda condition doesn't read as naturally. – Marko Topolnik Sep 06 '14 at 16:28
  • Sometimes a certain String not being null can be an important condition for the program to work, so it is not necessarily good to avoid the NullPointerException. Just depends of the context. – Dici Sep 06 '14 at 16:30
  • Always use LHS literal as static analysis tools aren't smart enough to work out the context. It reads just as naturally for most people ;) Also never trust the lines before your condition, codes changes, just because it can't yield null today might not be true tomorrow after someone else edits it... – Adam Sep 06 '14 at 16:34
0

do it this way

        Scanner input = new Scanner(System.in);
        String komanda = "a";
        do { 
            System.out.println("Unesi komandu ");
            komanda = input.nextLine();
        }
        while(!"start".equals(komanda));
        System.out.println("Bravo");
Nadir Belhaj
  • 11,953
  • 2
  • 22
  • 21