Monday, July 21, 2014

Math Test Chapter 3, Exercise 1

Chapter 3 Exercise 1
Improve the multiplication game from the previous chapter. We will randomly ask the player to either add, multiply, or subtract one-digit numbers (we skip division because the result of dividing two numbers is not an integer). The game should ask 10 math questions and record the answers. At the end, the game should tell the player how well they did, that is, how many questions they answered correctly.

import java.util.*;
public class MathTest {
public static void main(String[] args) {
Random randomGenerator = new Random();
int x = 1;// first number in equation
int y = 1;// second number in equation
int z = 1;// determines operation
int answer = 0;// correct answer
int score = 0;// how many user gets right
int result = 0;// user input
String op = "";// string correlating to random operation
Scanner keyboard = new Scanner(System.in);

for (int a = 1; a <= 10; a++) {// do this 10 times
x = randomGenerator.nextInt(10);// get random integer 0-9
y = randomGenerator.nextInt(10);// get random integer 0-9
z = randomGenerator.nextInt(3);// get random integer 0-2
if (z == 0) {// if addition
op = "+";
answer = x + y;
} else if (z == 1) {// if subtraction
op = "-";
answer = x - y;
} else if (z == 2) {// else multiplication
op = "*";
answer = x * y;
}
System.out.print(x + " " + op + " " + y + " = ");// prompt user
result = keyboard.nextInt();// get answer
if (result == answer) {// if answer is correct
System.out.println("correct");// print correct
score++;// increase score
} else {
System.out.println("incorrect");// print incorrect
}
}
keyboard.close();
System.out.println("Your score is " + score + "/10.");// print score
}
}


No comments:

Post a Comment