Why can't I use 'continue' inside a switch statement in Java?

后端 未结 7 433
醉梦人生
醉梦人生 2020-12-10 16:47

Why is it that the following code:

class swi  
{
    public static void main(String[] args)  
    {  
        int a=98;
        switch(a)
        {
                  


        
7条回答
  •  无人及你
    2020-12-10 17:23

    Because you have a continue outside of a loop. continue is for jumping back to the beginning of a loop, but you don't have any loop in that code. What you want for breaking out of a switch case block is the keyword break (see below).

    There's also no need to put every case block within braces (unless you want locally-scoped variables within them).

    So something a bit like this would be more standard:

    class swi22
    {
        public static void main(String[] args)
        {
            int a=98;
            switch(a)
            {
                default:
                    System.out.println("default");
                    break;
                case 'b':
                    System.out.println(a);
                    break;
                case 'a':
                    System.out.println(a);
                    break;
            }
            System.out.println("Switch Completed");
        }
    }
    

    There's also a school of thought that says the default condition should always be at the end. This is not a requirement, just a fairly widely-used convention.

提交回复
热议问题