Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.Scanner;
- import java.lang.Math;
- public class Main
- {
- // instance variables - replace the example below with your own
- private int x;
- /**
- * Constructor for objects of class Main
- */
- public static void main(String[] args)
- {
- System.out.println("Random Number Guessing Game");
- Scanner sc = new Scanner(System.in);
- Random rand = new Random();
- System.out.print("Insert minimum number range: ");
- int minVal = sc.nextInt();
- System.out.print("Insert maximum number range: ");
- int maxVal = sc.nextInt();
- int range = maxVal - minVal + 1;
- int guessNum = minVal + rand.nextInt(range);
- int input;
- for(int i = 1; true; i++) {
- System.out.println("Guess the number! ");
- input = sc.nextInt();
- if (guessNum == input) {
- onSuccessful(i, range);
- break;
- } else if (input < guessNum){
- System.out.println("Wrong, number is larger than " + input);
- } else if (input > guessNum){
- System.out.println("Wrong, number is smaller than " + input);
- }
- }
- }
- private static void onSuccessful(int attempts, int range) {
- System.out.println("Correct! You got the number after " + attempts + " tries");
- int optimalAttempts = (int) Math.ceil(Math.log(range + 1)/Math.log(2));
- if (attempts <= optimalAttempts) {
- System.out.println("Congratulations! You guessed the number with " +
- "the optimal number of tries!");
- } else {
- System.out.println("Altough you correctly guessed the number, you " +
- "could've gotten it in "+ optimalAttempts + " tries");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement