我正在尝试制作一个程序,如果您在 Java 控制台中输入“open”,它就会结束。
当我输入 open 时,下面的 if 语句不会运行。
if(input=="open") {
System.out.println("You escaped!!");
break;
}
我也试过 .equals 但它仍然不起作用
if(input.equals("open")) {
System.out.println("You escaped!!");
break;
}
但是,当我如下所示打印输入时,输入是打开的。这是没有意义的,因为如果输入是打开的,那么上面的 if 语句应该已经运行。
else{
//otherwise check what was written
System.out.println(input);
}
这是我的完整代码:
class Password {
public static void main(String args[]) throws java.io.IOException {
//holds letters put in
char letter;
//holds full line of input
String input;
for(;;){
input="";
//makes the input equal what was inputed on the line
for(;;){
//gets next char
letter=(char) System.in.read(); //get a char
//if the line hasn't ended then add that char to input
if(letter!='\n'){
input+=String.valueOf(letter);
}else{
//other wise line has ended so input is finished
break;
}
}
//if open was typed in then end the program
if(input.equals("open")) {
System.out.println("You escaped!!");
break;
}else{
//otherwise check the input
System.out.println(input);
}
}
}
}