guess the number java

Solutions on MaxInterview for guess the number java by the best coders in the world

showing results for - "guess the number java"
Angeline
25 Sep 2019
1import java.util.Scanner;
2import java.util.Random;
3
4public class GuessingGame{
5
6    public static void main(String[] args) {
7
8        int random, guess, attempts;
9        Scanner keyboard = new Scanner(System.in);
10        Random generator = new Random();
11        random = generator.nextInt(100) + 1;
12        attempts = 1; 
13
14        System.out.print("I am thinking of a number between 0 and 100, what do you think it is?");
15
16        guess = keyboard.nextInt(); 
17        while (guess != random) {
18            if (guess > random) {
19                System.out.print("Lower!");
20                attempts += 1; 
21            }
22            else {
23                System.out.print("Higher!");
24                attempts +=1;
25            } 
26        }
27
28        System.out.print(random + "is the correct answer and it took you" + attempts + "attempts to guess it!");
29
30    }        
31}