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");
}
}
}
}
Last edited by admin on Thu Apr 27, 2023 7:43 am, edited 1 time in total.
Reason:Please put code inside [code] [/code]
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?
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
If you like our products and services, please help us by posting your review here.
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.
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.
If you like our products and services, please help us by posting your review here.