Advertisement
SenpaiZero

Untitled

Apr 1st, 2024
579
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. import java.util.*;
  2. public class runGame {
  3.     public static void main(String[] args)
  4.     {
  5.         Scanner scanner = new Scanner(System.in);
  6.         String userInput;
  7.         int attemp = 0;
  8.        
  9.         System.out.println("Guess the number from 1 to 50");
  10.         int rand = new Random().nextInt(50); // Creating random number from 1 to 50
  11.        
  12.        
  13.         do
  14.         {
  15.             System.out.print("Enter: ");
  16.             userInput = scanner.nextLine(); //Get value from user
  17.             attemp++; //increase attemp each loop
  18.            
  19.             if(userInput.matches("\\d+")) //Check if user input is integer
  20.             {
  21.                 int val = Integer.valueOf(userInput);
  22.                 if(val == rand) break; //Stops the loop if user guessed the number
  23.                 if(val > rand)System.out.println("Too high. Try Again!"); //Check if user is higher than random number
  24.                 if(val < rand) System.out.println("Too low. Try Again!"); // Check if user is lower than random number
  25.             }
  26.             else {
  27.                 System.out.println("Invalid input!"); //print invalid if the user input is not integer
  28.             }
  29.            
  30.         } while(true); //Keep looping until the user guess the number
  31.        
  32.         //Print attemps when finished
  33.         System.out.println("You got it in " + attemp + " attemps!");
  34.     }
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement