samedi 31 octobre 2020

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

Aucun commentaire:

Enregistrer un commentaire