Forked from sanabanana-png/gist:eae2ec8401986a15b8e04b3ee870f9da
Created
January 27, 2023 19:00
-
-
Save mhaligowski/82dbddb1e0d05e8e8904ab4ed10e074b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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