Switch statement within Do-While loop doesn't exit

The code doesn't exit after I type "stop" - for some reason. Why? Step-by-step debugging shows that after I enter "stop" it's value consists of exactly 's','t','o','p' without any line breaks, etc. - however, the code still goesn't exit. Could anyone tell why, please?

import java.util.Scanner;

public class Application {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    // asking username
    System.out.print("Username: ");
    String username = input.nextLine();

    String inpText;
    do {
        System.out.print(username + "$: ");
        inpText = input.nextLine();
        System.out.print("\n");
        // analyzing
        switch (inpText) {
        case "start":
            System.out.println("> Machine started!");
            break;
        case "stop":
            System.out.println("> Stopped!");
            break;
        default:
            System.out.println("> Command not recognized");
        }
    } while (inpText != "stop");

    System.out.println("Bye!..");
}
}

Answers


  • To compare Strings use .equals() and not ==, unless you really know what you are doing.
inpText != "stop" //Not recommended
!"stop".equals(inpText) //recommended

Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted


Need Your Help

Move window by dragging background (movableByWindowBackground)

osx cocoa nswindow

I have a window that I want users to be able to move by dragging anywhere in the window content (not just the titlebar). I know that this can be done via the NSWindow movableByWindowBackground met...

GStreamer add probe with playbin

gstreamer

The following code adds a callback when each frame is displayed and it's working well:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.