6: When Loops are More Predictable than Lunch Menus
Hey KISJ warriors! 🚀 Before we dive in, a big shoutout to everyone for the recent formative! Whether you aced it or faced some challenges, remember it covered a lot from Day 1 to 5. So, kudos for navigating through it! Now, remember those days when you'd loop around the cafeteria trying to decide if today's lunch was edible or if you'd be better off with a snack from the deli? Well, Java's loops are kinda like that, but without the disappointment. Let's dive deeper!
Counted Loops: The Cafeteria Rounds
Just like how you might circle the cafeteria a few times before choosing a meal, counted loops in Java let your program run a set of instructions multiple times.
Back in the day, with only the do-while loop, our code looked like someone lost in the cafeteria:
int x = 0;
do {
// Pondering lunch choices here
x += 1;
} while (x < 10);
But thanks to the counted loop, we've got a more efficient way to make our rounds:
The 'For' Loop: The Lunch Line Strategy
for (int count = 0; count < 10; count++) {
// Picking food items here
}
With the for
loop, the variable count
is like that friend who only joins you for lunch and disappears afterward. It exists only within the loop's scope.
- The
for
statement has a counter, kind of like counting how many times you've been disappointed by the lunch menu. - You can use the counter value inside the loop, like tallying up the number of decent meals.
- The counter variable doesn't linger around after the
for
statement, just like that mystery meat from last week.
'For' Loop Examples: The Lunch Menu
Counting to 10 (like counting the number of veggies on your plate):
for (int i = 0; i < 10; i++) {}
Counting to 10 with 2 added (like adding two extra fries because why not):
for (int c = 0; c < 10; c = c + 2) {}
Looping 'num' times (like checking the dessert corner num
times):
for (int i = 0; i < num; i++) {}
Decreasing counter (like counting down the minutes until lunch is over):
for (int i = 100; i >= 10; i--) {}
Break, Continue, and System.exit(): The Lunchtime Escape Tactics
Sometimes, you just want to leave school on lunch. Here's how you can do it in Java:
- Use
break;
when you spot that unidentifiable dish and want to exit the loop. - Use
continue;
when you want to skip over the salad and see what's next. - And
System.exit()
? That's like seeing the lunch line and deciding to just go home.
But remember, just like ditching lunch isn't always the healthiest choice, using these commands can make your code less efficient. Java likes to plan ahead, and using break or continue can mess up its game plan.
That's it for today's lesson on Java loops! If you've missed our previous lessons, don't worry. They're more accessible than the deli during lunchtime rush. Dive in, and remember: Java loops might be more predictable than tomorrow's lunch menu. 😉 Happy coding! 🎉👩💻👨💻