0

I'm trying to make a program in which if you type in "open" to the java console it ends.

When I type in open, the if statement below doesn't run.

            if(input=="open") {
                System.out.println("You escaped!!");
                break;
            }

I've also tried .equals and it still doesn't work

    if(input.equals("open")) {
        System.out.println("You escaped!!");
        break;
    }

However when I print out input as shown below, the input is open. This makes no sense because if the input was open, then the if statement above should have run.

            else{
                //otherwise check what was written
                System.out.println(input);
            }

Here is my full code:

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);
            }
        }
    }

}

Zachooz
  • 535
  • 11
  • 25

0 Answers0