exercise: creating a Labeled while Loop: anyone can help me to check?
adam Lui
Ranch Hand
Joined: Sep 03, 2007
Posts: 186
posted
0
i am not sure if the code i created is correct, it does run, but just not confident enough to say it is correct! it's not long, pls help!
Exercise question: Try creating a labeled while loop. Make the label outer and provide a condition to check whether a variable age is less than or equal to 21. Within the loop, increment age by one. Every time the program goes through the loop, check whether age is 16. If it is, print the message "get your driver's license" and continue to the outer loop. If not, print "Another year."
=====================My code is as below======================= class ex52{ public static void main (String args[]){ int age = 0; outer: while (age <= 21) { if (age == 16) { System.out.println ("Get your driver's license " + age); } else { System.out.println ("Another year " + age); } age++; System.out.println ("incrementing age"); continue outer; } } }
boolean b = true;<br />System.out.println ("I believe in Java.<br />Java will make my dream come " + b);
Ajay Divakaran
Greenhorn
Joined: Jul 08, 2007
Posts: 22
posted
0
The code is correct!
Tony Smith
Ranch Hand
Joined: Jul 07, 2007
Posts: 229
posted
0
I believe the program is correct however I would double check with where you get the instruction from; because instruction doesn't make much sense. Because this program doesn't even test out the purpose of labeled while loop. Notice if you remove the continue outer; the program would run exactly the same way. So that line doesn't do anything. Usually if you want to test labeled outer loop, meaning you have to somehow get stuck in the inner loop somwhere. But there is no inner loop.
Also you might want to post this question in the java beginner section instead of SCJP. This is the wrong place to post this question.
Vikrant Sahdev
Ranch Hand
Joined: May 31, 2007
Posts: 58
posted
0
Your continue statment should be under the if block testing condition :
Actually I wrote the same code but,
What should the output for this code?
Stuart A. Burkett
Ranch Hand
Joined: May 30, 2012
Posts: 321
posted
0
ketki patil wrote:Actually I wrote the same code but,
What should the output for this code?
adam Lui wrote:Every time the program goes through the loop, check whether age is 16.
If it is, print the message "get your driver's license" and continue to the outer loop. If
not, print "Another year."