Arif Aqmar
Arif Aqmar

Reputation: 11

Java if else in while loop

i had this problem where while looping, the output shows the loop but the invalid is also there. how do i separate the loop and the if...else statements?

below is the program code.

Scanner scan = new Scanner(System.in);
String option = new String("Y");

while (option.equalsIgnoreCase("Y")) {
    System.out.println("Good Morning!!");
    System.out.print("Do you want to continue [Y/N]: ");
    option = scan.nextLine();

    if (option.equalsIgnoreCase("N")) {
        break;

    } else {

        System.out.println("invalid");
    }
}

this is the output of the loop. the invalid is only supposed to show up when i put in a different letter other than y or n

Do you want to continue [Y/N]: y
invalid
Good Morning!!
Do you want to continue [Y/N]: y
invalid
Good Morning!!

and it was supposed to show like this

Good Morning!!
Do you want to continue [Y/N]: y
Good Morning!!
Do you want to continue [Y/N]: y
Good Morning!!
Do you want to continue [Y/N]: n

Upvotes: 0

Views: 1020

Answers (3)

Tomas Calaf Marti
Tomas Calaf Marti

Reputation: 11

You're just cheking if it's a "N" but not a "Y" so it'll will show invalid for Y. You just have to add another else if and the last else with the invalid.

Scanner scan = new Scanner(System.in);
String option = new String("Y");

while (option.equalsIgnoreCase("Y")) {
    System.out.println("Good Morning!!");
    System.out.print("Do you want to continue [Y/N]: ");
    option = scan.nextLine();

    if (option.equalsIgnoreCase("N")) {
        break;

    }else if(option.equalsIgnoreCase("Y")){
        continue; 
    }else {
        System.out.println("invalid");
   }
}

Upvotes: 1

Nowhere Man
Nowhere Man

Reputation: 19545

You could also implement else if to check for acceptable character and remove the redundant check from the condition in while:

while (true) {
    System.out.println("Good Morning!!");
    System.out.print("Do you want to continue [Y/N]: ");
    String option = scan.nextLine();

    if (option.equalsIgnoreCase("N")) {
        break;
    } else if (!option.equalsIgnoreCase("Y")) {
        System.out.println("invalid");
    }
}

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

Scanner scan = new Scanner(System.in);

while (true) {
    System.out.println("Good Morning!!");
    System.out.print("Do you want to continue [Y/N]: ");
    String option = scan.nextLine().toUpperCase();

    if ("N".equals(option))
        break;
    if ("Y".equals(option))
        continue;

    System.out.println("invalid");
}

Upvotes: 0

Related Questions