For this project you will write a Java program that will run a simple math quiz. Your program will generate two random integers between 1 and 20 and then ask a series of math questions. Each question will be evaluated as to whether it is the right or wrong answer. In the end a final score should be reported for the user. (See below for how to generate random numbers).
Sample Ouptut This is a sample transcript of what your program should do. Values in the transcript in BOLD show the user inputs. So in this transcript the user inputs 33, Jeremy, 24, -16, and 80 the rest is output from the program.
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double x = new Random().nextInt(20) + 1;
double y = new Random().nextInt(20) + 1;
double answer;
int correctAnswers = 0;
String[] questions = {x + "+" + y + "=", x + "-" + y + "=", x + "*" + y + "=", x + "/" + y + "=",};
for (int i = 0; i < questions.length; i++) {
System.out.print(questions[i]);
while (true) {
try {
answer = Double.parseDouble(in.nextLine());
switch (i) {
case 0:
if (answer == x + y) {
correctAnswers++;
System.out.println("Correct.");
} else {
System.out.println("Incorrect.");
}
break;
case 1:
if (answer == x - y) {
correctAnswers++;
System.out.println("Correct.");
} else {
System.out.println("Incorrect.");
}
break;
case 2:
if (answer == x * y) {
correctAnswers++;
System.out.println("Correct.");
} else {
System.out.println("Incorrect.");
}
break;
case 3:
if (answer == x / y) {
correctAnswers++;
System.out.println("Correct.");
} else {
System.out.println("Incorrect.");
}
break;
}
break;
} catch (NumberFormatException e) {
System.out.println("Enter a number!");
}
}
}
System.out.println(correctAnswers + "/" + questions.length);
}
}
Comments
Leave a comment