Skip to content
Advertisement

I can’t loop my code whenever condition fails. It just prints both blocks of code if the user input is true

I am a beginner at java and I want to loop this all over again but I don’t know how. I’ve tried a while loop but it doesn’t work really well and it prints both blocks of code. What should happen is when I type “quit, Quit, or QUIT”, it should terminate. What happens instead is that it also prints the message “failed to terminate the program”. What should I do? I’ve also tried an if statement which works fine but I don’t know how to loop it if the condition fails.

import java.util.Scanner;

public class fortytwo {

    public static void main(String[] args) {
    
        Scanner scanner = new Scanner(System.in);
        System.out.println("Hi there!");
        String quit = scanner.next();
                
        while (quit.equals("quit") || quit.equals("QUIT") || quit.equals("Quit")) {
            System.out.println("You terminated the program");
            break;
        } 
        System.out.println("You failed to terminate the program.n To quit, type (quit), (Quit), or (QUIT)");
            
        scanner.close();
    }
}

Advertisement

Answer

The condition of the loop is to check while quit is NOT equal to "quit" (regardless of the case), so the message "You failed to terminate the program..." should be printed in the loop body until appropriate command is entered.

Also, assignment to quit may be omitted, and the method equalsIgnoreCase is recommended to invoke on the constant/literal value because in general case it helps avoid NullPointerException.

while (!"quit".equalsIgnoreCase(scanner.next())) {
    System.out.println("You failed to terminate the program.n To quit, type (quit), (Quit), or (QUIT)");
}
System.out.println("You terminated the program");
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement