Question

First thank you for reading. Also I'm very aware of how I can get this to work they way I want it to. I'm just experimenting and not getting expected results. When I run this code I would expect that when I enter the letter X I would be asked to try again and re-attempt to enter the letter B. Well, I am. However The program will then break to the start: label and process based on the new value of input we got in the default case. If on my second attempt I enter the letter B, nothing gets executed in the switch statement. If you enter the letter B on your second try, the program will print that you entered B and then the program will terminate. Why is this?

import java.util.Scanner;
public class Help
{
   public static void main(String[] args)
   {
      Scanner kb = new Scanner(System.in);
      System.out.println("Enter the letter B: ");
      char input = kb.nextLine().charAt(0);
      start:
      switch(input)
      {
         case 'B':
            System.out.println("Nice Work!");
            break;
         default:
            System.out.println("Try again: ");
            input = kb.nextLine().charAt(0);
            System.out.println(input);
            break start;

      }

   }
}
Était-ce utile?

La solution

The labeled break statement is meant for terminating loops or the switch statement that are labeled with the corresponding label. It does not transfer control back to the label. Your switch statement is simply falling through to the end of program, as it should.

A labeled break would only be helpful if you had nested switch statements and needed to break out of the outer one from the inner one.

See this for further information.

Autres conseils

Use while cycle:

import java.util.Scanner;
public class Help
{
   public static void main(String[] args)
   {
      Scanner kb = new Scanner(System.in);
      System.out.println("Enter the letter B: ");
      while(true)
      { 
        char input = kb.nextLine().charAt(0);
        switch(input)
        {
         case 'B':
            System.out.println("Nice Work!");
            break;
         default:
            System.out.println("Try again: ");
        }
      }

   }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top