我试图制作一个程序,如果你输入"打开"它以java控制台结束。
当我输入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);
}
}
}
}