Java 字符串在分配给 Scanner NextLine() 时未存储相同的值
Java String not storing same value when assigned to Scanner NextLine()
我的代码的控制台处理程序遇到了问题。不知道赋值给s.nextLine();
后读取in
会不会丢弃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);
}
}
当我在控制台中输入 kill
时,它给了我这个:
[info @ DEBUG/0]> User input: kill
[info @ CONSOLE/0]> Illegal Arguements given.
您应该使用 .equals()
方法检查字符串(和其他对象)是否相等,而不是使用 ==
运算符。
对于字符串比较,您应该使用 .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);
}
}
我的代码的控制台处理程序遇到了问题。不知道赋值给s.nextLine();
后读取in
会不会丢弃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);
}
}
当我在控制台中输入 kill
时,它给了我这个:
[info @ DEBUG/0]> User input: kill
[info @ CONSOLE/0]> Illegal Arguements given.
您应该使用 .equals()
方法检查字符串(和其他对象)是否相等,而不是使用 ==
运算符。
对于字符串比较,您应该使用 .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);
}
}