Search code examples
javajava.util.scannersystem.in

Java String not storing same value when assigned to Scanner NextLine()


I have come across a problem with the console handler of my code. I don't know if reading in after assigning it to s.nextLine(); discards the current value of in. Not sure if anything else could affect the String from being read correctly in one line, and incorrectly in the next.

Thanks in advance!

while (loop == true) {
        Scanner s = new Scanner(System.in);
        String a = s.nextLine();
        String in = a;
        info("User input: " + in, "DEBUG", 0);
        if (in == "kill") {
            info("Are you sure you would like to kill the running instance? [Y/N]", "CONSOLE", 0);
            if (in == "Y" || in == "y") {
                info("Starting KILL method.", "CONSOLE", 0);
                s.close();
                loop = false
            } else if (in == "N" || in == "n") {
                info("Cancelled.", "CONSOLE", 0);
            } else {
                info("Illegal arguements given. Cancelled.", "CONSOLE", 0);
            }

        } else {
            info("Illegal Arguements given.", "CONSOLE", 0);
        }

    }

When I typed kill in the console, it gave me this:

[info @ DEBUG/0]> User input: kill
[info @ CONSOLE/0]> Illegal Arguements given.

Solution

  • For String compare you should use .equals:

    while (loop == true) {
            Scanner s = new Scanner(System.in);
            String a = s.nextLine();
            String in = a;
            info("User input: " + in, "DEBUG", 0);
            if ("kill".equals(in)) {
                info("Are you sure you would like to kill the running instance? [Y/N]", "CONSOLE", 0);
                if ("Y".equals(in) || "y".equals(in)) {
                    info("Starting KILL method.", "CONSOLE", 0);
                    s.close();
                    loop = false
                } else if ("N".equals(in) || "n".equals(in)) {
                    info("Cancelled.", "CONSOLE", 0);
                } else {
                    info("Illegal arguments given. Cancelled.", "CONSOLE", 0);
                }
    
            } else {
                info("Illegal arguments given.", "CONSOLE", 0);
            }
        }