samer g :
So I have this code where the user enters a random number from 0 to 9 and has to guess the number but I want to limit the users trials to 4 once he guessed wrong 4 times the system stops and displays a message "you exceeded your allowed trials" this is my code so far:
public static void main(String[] args) {
// TODO Auto-generated method stub
int nb,x;
int count= 0;
Scanner inp= new Scanner(System.in);
nb= (int)(Math.random()*10);
System.out.print("Guess the number between 0 and 9");
x=inp.nextInt();
while(x!= nb) {
if(x>nb) System.out.println("Lesser");
else if (x<nb) System.out.println("Bigger");
System.out.println("Try another Number");
x=inp.nextInt();
count++;
}
System.out.println("Found!!");
System.out.println("Number of Guesses:" +count);
inp.close();
}
Sheri :
You can also used you count
variable to keep track of attempts, once user ends with limit you can exit the program by breaking the while
loop using break
statement.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
// TODO Auto-generated method stub
int nb,x;
int count= 1;
Scanner inp= new Scanner(System.in);
nb= (int)(Math.random()*10);
System.out.print(nb);
System.out.print("Guess the number between 0 and 9:");
x=inp.nextInt();
while(x!= nb) {
if (count <= 3){
if(x>nb) System.out.println("Lesser");
else if (x<nb) System.out.println("Bigger");
System.out.println("Try another Number");
x=inp.nextInt();
}
else{
System.out.print("you exceeded your allowed trials");
break;
}
count++;
}
System.out.println("Found!!");
System.out.println("Number of Guesses:" +count);
inp.close();
}
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=361046&siteId=1