Skip to content

Instantly share code, notes, and snippets.

@sanabanana-png
Created January 27, 2023 18:23
Show Gist options
  • Save sanabanana-png/eae2ec8401986a15b8e04b3ee870f9da to your computer and use it in GitHub Desktop.
Save sanabanana-png/eae2ec8401986a15b8e04b3ee870f9da 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();
ask();
}
public static void ask() {
System.out.println("Do you want to play again? (y/n)");
Scanner lastPrompt = new Scanner(System.in);
String answer = lastPrompt.nextLine();
if (answer.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.");
} 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.");
}
}
}
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