Skip to content

Instantly share code, notes, and snippets.

@rmg007
Created October 21, 2022 14:55
Show Gist options
  • Save rmg007/22dc884351add32688584dc5feeb43ff to your computer and use it in GitHub Desktop.
Save rmg007/22dc884351add32688584dc5feeb43ff to your computer and use it in GitHub Desktop.
Guess the Number
import java.util.Random;
import java.util.Scanner;
/*
lecture 130 in learn and dive deep in Java course
https://www.udemy.com/course/best-java-course/?referralCode=3F66CEAE090AA62ADCB2
*/
public class GuessTheNumber{
public static void main(String[] args) {
// intro
System.out.println("Number Guessing Game \uD83C\uDFB2");
displayLives(3);
System.out.println("Enter a guess between 1 and 10 \uD83E\uDD14");
// generate random number
int random = new Random().nextInt(10) + 1;
int lives = 3;
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
int guess = scanner.nextInt();
if(guess > random){
System.out.println("your guess is too high");
displayLives(--lives);
} else if(guess < random){
System.out.println("your guess is too loo");
displayLives(--lives);
}else{
System.out.println("Your number is correct. You won \uD83C\uDF89 \uD83E\uDD73");
break;
}
}
if(lives == 0){
System.out.println("You lost. good luck next time.");
}
scanner.close();
}
static void displayLives(int n){
StringBuilder sb = new StringBuilder("You have " + n + " lives ");
for (int i = 0; i < n; i++) {
sb.append("❤️");
}
System.out.println(sb);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment