begincoding123 begincoding123 - 29 days ago 8
Java Question

Terminate program when press "q"

I'm trying to terminate a program when user input "q". How can i stop the last two line of codes to not execute when user input "q"?
Here is my code:

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String expression = "";
while (!expression.equalsIgnoreCase("q")) {
System.out.println("Type an expression written in Infix notation: ");
expression = input.next();
PostFixConverter convert = new PostFixConverter(expression);
System.out.println("This expression writtien in Postfix notation is: \n" + convert.infixToPostfix());

}
}
}

PVR PVR
Answer

Instead of while use do-while loop if you want to iterate the code continuously based on user input.

Scanner input = new Scanner(System.in);
            String expression = "";

            System.out.println("Type an expression written in Infix notation: ");
            expression = input.next();

            if(!expression.equalsIgnoreCase("q"))
            {
                do{
                    PostFixConverter convert = new PostFixConverter(expression);
                    System.out.println("This expression writtien in Postfix notation is: \n" + convert.infixToPostfix());

                    System.out.println("Type an expression written in Infix notation: ");
                    expression = input.next();
                }while (!expression.equalsIgnoreCase("q"));
            }   
            }
        }