• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exercise: creating a Labeled while Loop: anyone can help me to check?

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
}
}
}
 
Ajay Divakaran
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code is correct!
 
Tony Smith
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your continue statment should be under the if block testing condition :
 
ketki patil
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually I wrote the same code but,
What should the output for this code?
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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."
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic