Skip to content

Instantly share code, notes, and snippets.

@sanabanana-png
Forked from mhaligowski/InputRandomGame.java
Created January 27, 2023 22:53
Show Gist options
  • Save sanabanana-png/5441384aad82869e4dcc41d5be1cbc25 to your computer and use it in GitHub Desktop.
Save sanabanana-png/5441384aad82869e4dcc41d5be1cbc25 to your computer and use it in GitHub Desktop.
import java.util.Random;
import java.util.*;
public class inputRandomGame {
public static void main(String[] args) {
intro();
gameMechanic();
}
public static void looper(){
System.out.println("Would you like to play again?(y/n)");
Scanner ask = new Scanner(System.in);
String question = ask.nextLine();
if(question.equals("y")) {
gameMechanic();
} else {
System.exit(0);
}
}
public static void gameMechanic() {
int randomInt = answerNum();
int userGuess = 0;
while (userGuess != randomInt) { //while user guess isnt the random number, it will keep repeating.
try { //every time the loop runs, it will TRY to do this
System.out.println("Enter number:");
Scanner obj = new Scanner(System.in);
int guess = obj.nextInt(); //it wants an integer, and if not ...
userGuess = guess;
if (randomInt == guess) {
System.out.println("Congrats! you guessed your number.");
looper();
} else if (randomInt > guess) {
System.out.println("Your input is too low. Try again!");
} else if (randomInt < guess) {
System.out.println("Your input is too high. Try again!");
}
}
catch (InputMismatchException ex) { //... if it's not an integer, it wil CATCH this and print out the input.
System.out.println("Invalid input, try again.");
}
}
looper();
}
public static int answerNum() {
Random rand = new Random();
int maxNum = 100;
int randInt = rand.nextInt(maxNum);
return randInt;
}
public static void intro() {
System.out.println("I am thinking of a number between 1-100.");
System.out.println("Can you guess what it is?");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment