Skip to content

Instantly share code, notes, and snippets.

@Apexal
Created February 2, 2017 23:02
Show Gist options
  • Save Apexal/ffa32c04500cf82d5bd6a47e05782799 to your computer and use it in GitHub Desktop.
Save Apexal/ffa32c04500cf82d5bd6a47e05782799 to your computer and use it in GitHub Desktop.
JaThs (Zaniac Anton Lesson 5)
import java.util.Scanner;
class Main {
// MATH GAME
// - Display random math expression to user
// - Allow user to type in the number
// - Every correct answer adds 1 point
// - User is allowed 3 mistakes
// - Game finishes when 4 mistakes are made
// - Displays final score to user
static int score = 0;
static int lives = 3;
public static int getAnswer(String operator, int int1, int int2) {
if (operator.equals("+")) {
return int1 + int2;
} else if (operator.equals("-")) {
return int1 - int2;
} else if (operator.equals("*")) {
return int1 * int2;
} else {
return int1 / int2;
}
}
public static String operationChoice() {
int random = 1 + (int)(Math.random() * ((4 - 1) + 1));
if (random == 1) {
return "+";
} else if (random == 2) {
return "-";
} else if (random == 3) {
return "*";
} else {
return "/";
}
}
public static void main(String[] args) {
String name;
Scanner keyboard = new Scanner(System.in);
// Get the name
System.out.print("Enter your name: ");
name = keyboard.nextLine();
// Show how to play the game
System.out.println("Hello, " + name + ". Welcome to JaThs! Try to answer as many questions as you can. You have " + lives + " lives.");
while(lives > 0) {
int int1 = 1 + (int)(Math.random() * ((100 - 1) + 1));
int int2 = 1 + (int)(Math.random() * ((100 - 1) + 1));
String operator = operationChoice();
System.out.print(int1 + " " + operator + " " + int2 + " = ");
int guess = keyboard.nextInt();
int answer = getAnswer(operator, int1, int2);
if (guess == answer) {
System.out.println("That's right!");
score++;
} else {
lives--;
System.out.println("Wrong! You have " + lives + " lives left.");
}
}
System.out.println("GAME OVER! You got " + score + " points!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment