Click here to Skip to main content
15,920,031 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have made a practice program in Java in which computer will save a random number in it's memory and the user has to guess it. Everytime user guesses a wrong number, The compiler asks to try again,But i want to set a limit into that program that if the user guesses the number 8 times,then the program stops. Any help would be appreciated.

What I have tried:

public static void main(String[] args) {
		Random nums = new Random();
		int ran= nums.nextInt(100);
		
		System.out.printf("Please enter a value: %n");
		
		Scanner scan = new Scanner(System.in);
		
		int Value1;
		do {
			
			
			 Value1= scan.nextInt();
			
			if(Value1 > ran) {
			System.out.println("You entered "+ Value1 + " which is greater than guess Please try again:");
			
		}else if (Value1 < ran){
			System.out.println("You entered "+ Value1 + " which is lesser than guess Please try again:");
		}else {
			System.out.println("Good job");
		}
			/*int tries= 8;
			for(int i=0; i ==tries;i++) {
			if(Value1==i) {
			System.out.println("Game Over");
			
			}
			}*/
			
		}while(Value1!=ran);
		scan.close();
		
	}
Posted
Updated 21-Jul-18 11:30am

1 solution

Here my suggestion. Include a variable to track number of attempt. If the number of guess > 8, display a message, exit the loop. If the user guess the correct number, exit the loop immediately. here is an example: https://www.jdoodle.com/embed/v0/zQq

Note: To test it, turn on the Interactive mode then click on Execute button.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900