The Program FlagControlledLoopjava uses a flagcontrolled whi
The Program FlagControlledLoop.java uses a flag-controlled while loop to implement the guessing the number game. However, the program gives as many tries as the user needs to guess the correct number. Modify this program to only allow the the user 5 attempts and on the 6th attempt the program will display a message like
\"You loose! too many attempts, Game Over!\"
//Flag-controlled while loop.
//Guessing the number game.
import java.util.*;
public class FlagControlledLoop
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
//declare the variables
int num; //variable to store the random number
int guess; //variable to store the number
//guessed by the user
boolean done; //boolean variable to control the loop
num = (int) (Math.random() * 100); //Line 1
done = false; //Line 2
while (!done) //Line 3
{ //Line 4
System.out.print (\"Enter an integer greater\"
+ \" than or equal to 0 and \"
+ \"less than 100: \"); //Line 5
guess = console.nextInt(); //Line 6
System.out.println(); //Line 7
if (guess == num) //Line 8
{ //Line 9
System.out.println(\"You guessed the \"
+ \"correct number.\"); //Line 10
done = true; //Line 11
} //Line 12
else if (guess < num) //Line 13
System.out.println(\"Your guess is \"
+ \"lower than \"
+ \"the number.\ \"
+ \"Guess again!\"); //Line 14
else //Line 15
System.out.println(\"Your guess is \"
+ \"higher than \"
+ \"the number.\ \"
+ \"Guess again!\"); //Line 16
} //end while //Line 17
} //Line 18
}
Solution
package test;
import java.util.*;
public class FlagControlledLoop
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
//declare the variables
int num; //variable to store the random number
int guess; //variable to store the number
//guessed by the user
boolean done; //boolean variable to control the loop
num = (int) (Math.random() * 100); //Line 1
done = false;//Line 2
int attempts=0;//Line 3
while (!done) //Line 4
{
if(attempts==5){ //Line 5
System.out.println(\"You loose! too many attempts, Game Over!\");//Line 6
break;//Line 7
}
System.out.print (\"Enter an integer greater\"
+ \" than or equal to 0 and \"
+ \"less than 100: \"); //Line 8
guess = console.nextInt(); //Line 9
System.out.println(); //Line 10
if (guess == num) //Line 11
{ //Line 12
System.out.println(\"You guessed the \"
+ \"correct number.\"); //Line 13
done = true; //Line 14
} //Line 15
else if (guess < num) { //Line 16
System.out.println(\"Your guess is \"
+ \"lower than \"
+ \"the number.\ \"
+ \"Guess again!\"); //Line 17
attempts++;//Line 18
}//Line 19
else { //Line 20
System.out.println(\"Your guess is \"
+ \"higher than \"
+ \"the number.\ \"
+ \"Guess again!\");//Line 21
attempts++;//Line 22
}//Line 23
} //end while //Line 24
} //Line 25
}

