课程: Learning Java 17

Using loops in Java - Java教程

课程: Learning Java 17

Using loops in Java

- [Instructor] Let's create a while loop in Java. In the previous lesson, we diagrammed a while loop to represent a song playing on repeat. If the current song is not on repeat, we exit the loop and play the next song. If the user never takes the song off repeat, the current song will play forever. We only exit the loop if the user takes the song off repeat. Let's jump to the code. The first thing we'll do is create a scanner to set us up for user input. We'll also create a Boolean variable that if the current song is on repeat. We'll start it off at true. We'll also import that scanner class. Now the while loop. While the current song is on repeat, meaning is on repeat is true, we want to run a series of statements. To do this, we'll use the keyword while and then our condition in parentheses. While is on repeat, we'll do what's in the curly brackets. Let's add those statements. We'll start out by printing that the current song is playing. On the next line, we'll ask the user if they want to take the song off repeat. After these print statements, we'll access the user's input with scanner.next. We'll save what the user inputs in a string called input. To check the user's answer, we can use an if statement. If yes equals the user's input, we'll want to take the song off repeat. So we'll set is on repeat equal to false. Equals is a string operation we can use to check if the user's input is a certain value. In this case, we check it with yes. If the condition is true, we set is on repeat to false because the user wants to take the song off repeat. All right, we're almost done. We just need to add a print statement for when the program exits the loop. We'll print out playing next song. Let's run it. Playing current song. We'll keep it on repeat. So we'll say, no. So we play it again. We'll answer no again. It's still on repeat. Let's take it off repeat. We'll answer yes and we move on to the next song.

内容