0

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
2

3 Answers 3

1

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");
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This doesn't explain what the changes were and why - it's just a code dumb, which isn't particularly helpful.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.