Advertisement
Guest User

Random Tebak Angka

a guest
Oct 23rd, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.Scanner;
  3. import java.lang.Math;
  4. public class Main
  5. {
  6.     // instance variables - replace the example below with your own
  7.     private int x;
  8.  
  9.     /**
  10.      * Constructor for objects of class Main
  11.      */
  12.     public static void main(String[] args)
  13.     {
  14.         System.out.println("Random Number Guessing Game");
  15.         Scanner sc = new Scanner(System.in);
  16.         Random rand = new Random();
  17.         System.out.print("Insert minimum number range: ");
  18.         int minVal = sc.nextInt();
  19.         System.out.print("Insert maximum number range: ");
  20.         int maxVal = sc.nextInt();
  21.         int range = maxVal - minVal + 1;
  22.         int guessNum = minVal + rand.nextInt(range);
  23.         int input;
  24.        
  25.         for(int i = 1; true; i++) {
  26.             System.out.println("Guess the number! ");
  27.             input = sc.nextInt();
  28.             if (guessNum == input) {
  29.                 onSuccessful(i, range);
  30.                 break;
  31.             } else if (input < guessNum){
  32.                 System.out.println("Wrong, number is larger than " + input);
  33.             } else if (input > guessNum){
  34.                 System.out.println("Wrong, number is smaller than " + input);
  35.             }
  36.         }
  37.     }
  38.    
  39.     private static void onSuccessful(int attempts, int range) {
  40.         System.out.println("Correct! You got the number after " + attempts + " tries");
  41.         int optimalAttempts = (int) Math.ceil(Math.log(range + 1)/Math.log(2));
  42.         if (attempts <= optimalAttempts) {
  43.             System.out.println("Congratulations! You guessed the number with " +
  44.             "the optimal number of tries!");
  45.         } else {
  46.             System.out.println("Altough you correctly guessed the number, you " +
  47.             "could've gotten it in "+ optimalAttempts + " tries");
  48.         }
  49.     }    
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement