I am fairly new to Java and I have an assignment that I have to create 5 questions and answers and have a user answer them. The program should then output the correct results out of five, as well as the percent and a feedback message. My code is as follows.
package quiz;
import javax.swing.*;
public class Quiz {
public static void main(String[] args) {
int count = 0;
final int totalQuestions = 5;
JOptionPane.showMessageDialog(null, "Welcome to the Trivia Program!");
JOptionPane.showMessageDialog(null, "A series of questions will be asked."
+ "\nPlease enter the letter of the answer"
+ "\nyou think is the correct choice.");
String[][] question = {
{"What letter is used to represent the number 100 in Roman Numerals?"
+ "\nA. M"
+ "\nB. D"
+ "\nC. C"
+ "\nD. X", "c"
},
{"Triton is the moon to which planet?"
+ "\nA. Jupiter"
+ "\nB. Neptune"
+ "\nC. Saturn"
+ "\nD. Uranus", "b"
},
{"What are Lanthanides?"
+ "\nA. Elements of the periodic table"
+ "\nB. Mountains on Earth"
+ "\nC. Mountains on the moon"
+ "\nD. Bacterium", "a"
},
{"What does a nidoligist study?"
+ "\nA. waves"
+ "\nB. clouds"
+ "\nC. bird nests"
+ "\nD. caves", "c"
},
{"Hypermetropic people are what?"
+ "\nA. obese"
+ "\nB. underfed"
+ "\nC. moody"
+ "\nD. far sighted", "d"
}
};
String[] answers = new String[totalQuestions];
for (int x = 0; x < totalQuestions; x++) {
answers[x] = JOptionPane.showInputDialog("\t\t" + (x + 1) + ". " + question[x][0] + " ");
answers[x] = answers[x].toLowerCase();
if (question[x][1].equals(answers[x])) {
JOptionPane.showMessageDialog(null, "Correct!");
count++;
} else {
JOptionPane.showMessageDialog(null, "Incorrect");
}
}
int avg = (count / totalQuestions) * 100;
switch (count) {
case 3:
JOptionPane.showMessageDialog(null, "You got " + count + "/" + totalQuestions + " correct"
+ "(" + avg + "%)"
+ "\nAverage");
break;
case 4:
JOptionPane.showMessageDialog(null, "You got " + count + "/" + totalQuestions + " correct"
+ "(" + avg + "%)"
+ "\nVery Good");
break;
case 5:
JOptionPane.showMessageDialog(null, "You got " + count + "/" + totalQuestions + " correct"
+ "(" + avg + "%)"
+ "\nExcellent!");
break;
default:
JOptionPane.showMessageDialog(null, "You got " + count + "/" + totalQuestions + " correct "
+ "(" + avg + "%)"
+ "\nPoor");
break;
}
}
}
My problem is that it only outputs the correct average % when all answers are correct (5/5). Anything else and the percentage is 0. Can anyone help explain this to me?