Java
Score calculation
Compute correct count and percentage with score.
Score calculation
The fourth lesson adds a method that calculates the score. A check method compares the given answer with the question's answer. A score field holds the count of correct answers. This is the quiz's core operation.
Example: int score = 0; int check(String[] answers) { for (int i = 0; i < count; i++) { if (answers[i].equals(questions[i].answer)) score++; } return score; }. This method compares each question's answer with the provided answers. If there is a correct match, score increases. The equals method is used for string comparison; == compares references and can give wrong results. The method returns the total count of correct answers.
equals vs ==
In Java strings are compared with equals. The == operator compares references, not content. Two strings with the same content can still return false with ==.
Example: new String("yes").equals(new String("yes")) returns true; because the content is the same. But new String("yes") == new String("yes") returns false; because two separate objects have different references. That is why equals is always used for string comparison. In quiz score calculation, answers[i].equals(questions[i].answer) is the correct approach. If you use ==, the score can always stay zero.
Exercise Add a check method to Quiz
Add an int score = 0 field to the Quiz class. Add an int check(String[] answers) method; in its body loop i from zero to count. At each step run if (answers[i].equals(questions[i].answer)) score++;. The method returns score. In main create a Quiz instance, add two questions, call check with String[] answers = {"Paris", "Berlin"} and print the result.
Show example solution
class Question {
String text;
String answer;
Question(String t, String a) {
text = t;
answer = a;
}
public String toString() {
return text + " = " + answer;
}
}
class Quiz {
Question[] questions;
int count;
int score;
Quiz() {
questions = new Question[10];
count = 0;
score = 0;
}
void add(Question q) {
questions[count] = q;
count++;
}
void display() {
for (int i = 0; i < count; i++) {
System.out.println(questions[i]);
}
}
int check(String[] answers) {
for (int i = 0; i < count; i++) {
if (answers[i].equals(questions[i].answer)) score++;
}
return score;
}
public static void main(String[] args) {
Quiz quiz = new Quiz();
quiz.add(new Question("Capital", "Paris"));
quiz.add(new Question("City", "London"));
String[] answers = {"Paris", "Berlin"};
System.out.println(quiz.check(answers));
}
}
Test yourself
-
Complete the equals comparison
if (answers[i].____(questions[i].answer)) {
score++;
}
Show answer
if (answers[i].equals(questions[i].answer)) {
score++;
}
-
Match the score parts
- int score
- Correct count
- answers[i].equals(...)
- Comparison
- score++
- Increment
- return score
- Return
-
Which method is used to compare two strings by content?
Show answer
equals — Equals — string content is compared with equals.
Next lesson: Putting it together