Develop a NUMBER GUESSING GAME using flag-controlled while loop in Java
Coding River
Develop a NUMBER GUESSING GAME using flag-controlled while loop in Java
Hi and welcome back to this channel, Let’s continue our discussion on while loop structures In today’s video, I am going to show you how to develop a Number Guessing Game, using a flag-controlled while loop. The game that we will develop must be able to prompt the user to guess the number that will be randomly generated by the program
But before that, let’s talk briefly about flag-controlled while loop Actually, a flag-controlled while loop is a loop that uses a boolean variable to control the execution of the loop The boolean variable is then called in programming terms, a flag variable
The code on the screen is a perfect example of how a flag-controlled while loop statement looks like
int score = 0; boolean isFound = false;
while ( !isFound ) { System.out.println (score + “ “); Score = score + 10;
if (score greater than or equal to 100) isFound = true; }
What we can note in this code is that the loop control variable is a boolean variable And as I said, that boolean variable is what we call a flag variable
The loop condition will test the flag variable If the loop condition is met Then the action statements in the body of the loop will execute
In the body of the loop, there is an if statement that is being used to update the loop control variable whenever the condition in the if statement evaluates to true
Let’s run this program and see what happens
Now, let’s develop our Number Guessing Game As I said at the beginning Suppose that we want to have a game that randomly generates an integer number greater than 0 and less than 100. The game must then prompt the user to guess the randomly generated number.
If the user guesses the number correctly, then the program will print out a specific message
If the number guessed by the user is not correct then the program checks to see if the number guessed is greater or less than the random number If the guessed number is less than the random number, the program will print out a message saying that “The number you guessed by the user is less than the random number” In case the number guessed by the user is greater than the random number, the program will have to print out a message saying that “The number you guessed by the user is greater than the random number”
The user will be prompted to guess the random number over and over again until he enters the correct number
So here is how the code will look like
I will start by creating an input object since I am going to use the keyboard as the source of input
import java.util.*; public class FlagControlledLoop { static Scanner console = new Scanner(System.in); public static void main(String[] args) {
The next thing to do is to declare the various vari ... https://www.youtube.com/watch?v=xa1_FbzzPoE
19168124 Bytes