Java字符串在分配给Scanner NextLine()时不存储相同的值

时间:2018-01-13 19:48:50

标签: java java.util.scanner system.in

我遇到了代码控制台处理程序的问题。我不知道在将in分配给s.nextLine();之后阅读in是否会丢弃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); } } 的当前值。不确定是否有任何其他因素可能会影响String在一行中正确读取,而在下一行中不正确。

提前致谢!

kill

当我在控制台中输入[info @ DEBUG/0]> User input: kill [info @ CONSOLE/0]> Illegal Arguements given. 时,它给了我这个:

((FirebaseFirestoreException)task.getException()).getCode()

2 个答案:

答案 0 :(得分:0)

您应该使用.equals()方法检查字符串(和其他对象)的相等性,而不是==运算符。

答案 1 :(得分:0)

对于String比较,你应该使用.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 arguements given. Cancelled.", "CONSOLE", 0);
            }

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

    }