课程: Learning Java 17
Understanding while loops
- [Presenter] IF statements aren't the only way we can add decision making to our programs. We also have loops. A loop is similar to an IF statement except it allows code to be repeatedly executed based on a condition instead of just one time. There are several different types of loops in Java, but the one we'll be focusing on in this course is the while loop. A while loop looks like this. We start at the start and then follow the arrow to check a condition. If the condition evaluates to true, we execute a series of statements and then check the condition again. If condition is false, we exit the loop and continue to the rest of the code. On your smartphone, you've probably listened to music. If you find a song you like you put the song on repeat. When a song is on repeat it plays over and over again until you take it off repeat. We can represent this type of functionality in a Java program. Filling in the condition of the while loop, we can say our condition is isCurrentSongOnRepeat. This will be a Boolean variable evaluating to true or false. If the condition is true we can print playing same song again and give an option for the user to take the song off repeat. If the condition is false, we can print out playing next song. Now, if isCurrentSongOnRepeat is never true, then playing same song again will never be printed. If the user never takes the song off repeat, then the condition will always be true and playing same song again will be continuously printed. That's why we call it a while loop. While the condition is true, keep running these given statements. Now that's a while loop. Let's try implementing it.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。