Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class runGame {
- public static void main(String[] args)
- {
- Scanner scanner = new Scanner(System.in);
- String userInput;
- int attemp = 0;
- System.out.println("Guess the number from 1 to 50");
- int rand = new Random().nextInt(50); // Creating random number from 1 to 50
- do
- {
- System.out.print("Enter: ");
- userInput = scanner.nextLine(); //Get value from user
- attemp++; //increase attemp each loop
- if(userInput.matches("\\d+")) //Check if user input is integer
- {
- int val = Integer.valueOf(userInput);
- if(val == rand) break; //Stops the loop if user guessed the number
- if(val > rand)System.out.println("Too high. Try Again!"); //Check if user is higher than random number
- if(val < rand) System.out.println("Too low. Try Again!"); // Check if user is lower than random number
- }
- else {
- System.out.println("Invalid input!"); //print invalid if the user input is not integer
- }
- } while(true); //Keep looping until the user guess the number
- //Print attemps when finished
- System.out.println("You got it in " + attemp + " attemps!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement