Created
March 24, 2013 16:31
-
-
Save will-y/5232562 to your computer and use it in GitHub Desktop.
Math equation game
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
package videogaming; | |
import javax.swing.*; | |
public class Game_NumberCruncher { | |
private static class MathProblem { | |
private String question; | |
private int answer; | |
public MathProblem() { | |
int num1 = (int) (Math.round(Math.random() * 10)); | |
int num2 = (int) (Math.round(Math.random() * 10) + 1); | |
int sign = (int) (Math.round(Math.random() * 4)); | |
if (sign == 0) { | |
question = num1 + " * " + num2; | |
answer = num1 * num2; | |
} else if (sign == 1) { | |
question = num1 + " / " + num2; | |
answer = num1 / num2; | |
} else if (sign == 2) { | |
question = num1 + " + " + num2; | |
answer = num1 + num2; | |
} else if (sign == 3) { | |
question = num1 + " - " + num2; | |
answer = num1 - num2; | |
} else { | |
question = num1 + " % " + num2; | |
answer = num1 % num2; | |
} | |
} | |
public String getQuestion() { | |
return question; | |
} | |
public int getAnswer() { | |
return answer; | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
// Variables | |
int numcorrect = 0; | |
String input = JOptionPane | |
.showInputDialog("How many problem do you want to answer"); | |
for (int i = 0; i < Integer.valueOf(input); i++) { | |
MathProblem mathProblem = new MathProblem(); | |
try { | |
String userAnswer = JOptionPane | |
.showInputDialog("What is the answer for " | |
+ mathProblem.getQuestion()); | |
if (Integer.valueOf(userAnswer) == mathProblem.getAnswer()) { | |
showMessage("You got it right!"); | |
numcorrect++; | |
} else { | |
showMessage("You are stupid the answer is " | |
+ mathProblem.getAnswer()); | |
} | |
} catch (NumberFormatException e) { | |
showMessage("You didn't even type a number!"); | |
} | |
} | |
showMessage("You got " + numcorrect + " out of " + input | |
+ " Right!"); | |
} | |
private static void showMessage(String message) { | |
JOptionPane.showMessageDialog(null, message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment