• Sign Up
• Login
• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Untitled

a guest Dec 8th, 2019 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import java.util.Random;
2. import java.util.Scanner;
3.
4.
5. public class GuessTheNumber {
6.
7.     // Maximum number the solution can be
8.     private final int max;
9.
10.     // Solution number
11.     private final int solution;
12.
13.     // Reads input from the user
14.     private final Scanner scanner;
15.
16.     // Constructor: picks a solution in range 0..maximum
17.     public GuessTheNumber(Scanner scanner, int max) {
18.         this.scanner = scanner;
19.         this.max = max;
20.         this.solution = new Random().nextInt(max);
21.     }
22.
23.     // Main game logic
24.     public void play() {
25.         while(true) {
26.             // Prompt the user to pick a number
27.             System.out.print("Enter your guess: ");
28.             int guess = scanner.nextInt();
29.
30.             // Check how the guess compares to the solution
31.             if (guess > solution) {
32.                 System.out.println("Number was too big!");
33.             } else if (guess < solution) {
34.                 System.out.println("Number was too small!");
35.             } else {
36.                 System.out.println("BINGO!");
37.                 break;
38.             }
39.         }
40.     }
41.
42.     public static void main(String[] args) {
43.         Scanner scanner = new Scanner(System.in);
44.
45.         // Get the maximum number from the user
46.         System.out.print("Enter maximum number: ");
47.         int max = scanner.nextInt();
48.
49.         // Start the game
50.         GuessTheNumber game = new GuessTheNumber(scanner, max);
51.         game.play();
52.     }
53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top