Page 1 of 1

switch

Posted: Wed Apr 26, 2023 9:36 am
by hin1129
I am struggling to understand why the output is C and F. Could someone explain this for me please :(

What letters will be printed by this program?

Code: Select all

public class ForSwitch
{
    public static void main(String args[])
    {
        char i;
        LOOP: for (i=0;i<5;i++)
        {
            switch(i++)
            {
                case '0': System.out.println("A");
                case 1: System.out.println("B"); break LOOP;
                case 2: System.out.println("C"); break;
                case 3: System.out.println("D"); break;
                case 4: System.out.println("E");
                case 'E' : System.out.println("F");
            }
        }
    }
}

Re: switch

Posted: Thu Apr 27, 2023 7:44 am
by admin
Where exactly are you stuck? If you can tell which part you have trouble understanding, we can help better.

Re: switch

Posted: Thu Apr 27, 2023 9:04 am
by hin1129
based on my understanding the program should do the following:

when i=0, case '0' is not true as '0' is char not int
when i=1, case 1 should be true as char could hold positive integer from 0 to 2^16 -1, hence it should print 'b' and terminate the loop

so i am confused about how the loop got to 2 and all the way to e
and why was d not printed if c was printed?

Re: switch

Posted: Thu Apr 27, 2023 11:34 am
by admin
Your logic is correct but you are missing the point that i is being incremented twice. Once by the for loop and once because of switch(i++). So, in the second iteration of the loop, i is actually 2 and not 1.
You may add a print statement at the beginning of the for loop to check the value of i. You will see 0 2 4 instead of 0 1 2 3 4 5

Re: switch

Posted: Tue May 02, 2023 5:33 pm
by Maria Teresa Lorenzo
I tried compiling this code and gives me this compile error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The label LOOP is missing

at ForSwitchjava.main(ForSwitchjava.java:15)
I also get a warning with the top LOOP label saying: The label LOOP is never explicitly referenced.
Any ideas how to fix this issue with the labels? I am using java 8.

Thank you.

Re: switch

Posted: Tue May 02, 2023 11:10 pm
by admin
I just copied the code you posted above and it compiled and ran fine without any issue. So it seems like you have something else going on with your environment or you have not copied the code correctly. Do this:
1. Open CMD prompt and cd to your work folder, e.g. c:\temp\javatest
2. create ForSwitch.java text file there using notepad and paste the above code exactly as it is.
3. From cmd line, compile using command:
c:\temp\javatest>javac ForSwitch.java
4. Run it:
c:\temp\javatest>java ForSwitch

That should work.