Code:
import java.util.*; public class HighLowGuessingGame { public static void main(String[] args) { Random random = new Random(); Scanner scanner = new Scanner(System.in); int number = random.nextInt(100)+1; int guess = -1; int count=0; while(guess!=number){ Beginning: while (guess!=number) { count=count+1; System.out.print("Enter a number between 1 and 100: "); guess = scanner.nextInt(); while (guess<number) { System.out.println("Too low, please try again"); break Beginning; } while (guess>number) { System.out.println("Too high, please try again"); break Beginning; } } } System.out.println("Correct, the number was " + number); System.out.println("It took you " + count + " trys."); } }
Output:
$ java HighLowGuessingGame Enter a number between 1 and 100: 50 Too low, please try again Enter a number between 1 and 100: 75 Too high, please try again Enter a number between 1 and 100: 63 Too low, please try again Enter a number between 1 and 100: 69 Too low, please try again Enter a number between 1 and 100: 72 Too high, please try again Enter a number between 1 and 100: 70 Correct, the number was 70 It took you 6 trys.