How to write a methood to count the number of correct answers in trivia game?

I'm new to Java and for an assignment we have to write a trivia game that gives the player a 2 attempts to guess the answer. Then at the end of the game we have to count how many questions they got wrong.

I've written pseudocode for a method that can count number of attempts but I'm not sure how to write it and use the for loop to count whether the question was right/wrong then count. This includes those guessed correctly on the first try, and those changed to be correct after an initial incorrect response.

If anyone could help me I'd appreciate it!

import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); //Introduction System.out.println("Welcome to the Animal Answers Trivia Game!"); System.out.println("You will be answering questions about various animals and " + "tested on your knowledge of furry critters to slimy snakes."); //Ask at least 5 questions and prompt for answers. //First Question System.out.println("What types of animal(s) can't vomit?"); String input = scan.nextLine(); //get input String answer = "Rodents"; public void guess (); //Second Question System.out.println("What is the only mammal capable of flight?"); String input = scan.nextLine(); //get input String answer = "Bats"; public void guess (); //Third Question System.out.println("What mammal has the most powerful bite"); String input = scan.nextLine(); //get input String answer = "Hippos"; public void guess (); //Fourth Question System.out.println("Where is the only place that dogs have sweat glands?"); String input = scan.nextLine(); //get input String answer = "paws"; public void guess (); //Fifth Question System.out.println("What is a male duck called?"); String input = scan.nextLine(); //get input String answer = "drake"; public void guess (); //Closing message with how many answers were correct public void correct (guess) { int correct = 0 // for(get questions and answers) //if answer correct { //increment correct //} //} return correct //Write any additional methods you need here public static boolean guess (String answer, Scanner input){ int guess = 0; for (int guess = 0; guess < 2; guess++) { if (input.nextLine().equalsIgnoreCase(answer)) { System.out.println("Good job, you got the correct answer!"); } else { System.out.println("Try again!"); if (input.nextLine().equalsIgnoreCase(answer)) { //need a nested if else this is if they got it wrong the second time System.out.println("Good job, you got the correct answer! Let's move onto the next question") } else { System.out.println("Sorry! Answer is incorrect. Time for the next question!"); } } guess++; } } 
1

3 Answers

You'll have to keep that state while going through the questions. You've already declared public static boolean guess(), but you're not actually returning a boolean. So change that to return based on answer correct or not.

Then where you now have public void guess (); in the main method, replace that with a guess call and increment the total number of correct answers if the method returns true.

First, I'd like for you to complete and run the code you do have. Remove these lines: each public void guess ();, public void correct (guess) {. Also, be sure the { and } are properly paired and nested. Bear in mind that you cannot code one method inside another. This example is correct:

 public static void main (String [] args) { // code for main } // end of main public static int foo (int arg) { // code for foo } // end of foo public static boolean bar (String bat) { // code for bar } // end of bar 

But, this is incorrect:

 public void static main (String [] args) { // some code for main public static int foo (int value) { // some code for foo } // end of foo } // end of main 

In addition, if you have a method that has a non-void return type, the code in the method must return a value of the specified type, via any execution path in that method. For example, if you have an int return type, the code must have a return statement with an int expression. The expression may be a constant. For an int return type method, the following are valid:

  • return 3;
  • return arg * arg + 7;
  • return foo;

When you get a clean compile, run your code. With at least one question, give no correct answer.

I suspect that, having done that, you don't need much more help

Let's continue with a design tip. This part is optional. You have repeated code. It might be that your teacher, at this point, wants you to have repeated code, because the next lesson will be about how to avoid repeated code.

When you want to have code that repeats, consider using some combination of the following:

  • Looping
  • An array or Collection, such as an ArrayList
  • Additional methods.
  • Additional class definitions.

Since you are new to Java, I assume Collection Objects will be in a future lesson.

Your code has several pairs, with each pair has one question and one answer. One way to pair a question with an answer is to use a new class:

public class QuizEntry { private String question; private String answer; public QuizEntry (String question, String answer) { this.question = question; this.answer = answer; } public String getQuestion () { return question; } public String getAnswer () { return answer; } } 

With that, you could have an array of QuizEntry:

 QuizItem [] theQuiz = { new QuizItem ("What types of animal(s) can't vomit?","rodents") , new QuizItem ("What is the only mammal capable of flight?","bats") // etc. }; 

If the items making a pair are of the same type, an alternative is to use a 2D array:

 String [][] theQuiz = { {"What types of animal(s) can't vomit?","rodents"} ,{"What is the only mammal capable of flight?", "bats"} // etc. }; 

Now, you can have a loop to run your quiz. But, before we get to that, there is a conflict in getting and handling the answers. In your code, taking one question as an example, you have this:

 System.out.println("What is the only mammal capable of flight?"); String input = scan.nextLine(); //get input String answer = "Bats"; 

In the above, the question is displayed, the user's answer is retrieved and awaits processing. Processing is presumably to be handled by the public static boolean guess (String answer, Scanner input) method. The problem is that method also gets the answer from the user. That means the user has to enter an answer twice before the answer is evaluated. The first response is ignored. The second is processed. If the second user response is incorrect, a third response will be processed.

Now, back to the loop:

 // 1D array with class QuizEntry version int correct = 0; for (int question = 0; question < theQuiz.length; question++) { System.out.println (theQuiz[question].getQuestion ()); ******* guess (theQuiz[question].getAnswer (), scan); ******* } 
 // 2D array version int correct = 0; for (int question = 0; question < theQuiz.length; question++) { System.out.println (theQuiz[question][0]); ******* guess (theQuiz[question][1], scan); ******* } 

Now, update your code and run it. Don't worry about finishing the part that counts correct answers. Oh, and remove the *******. It won't compile with them. Doing this reflects the "code a little, test a little" practice. If you have not already found and fixed it, you might find there is still a bug in the guess method.

Now, where I have the *******, you should make more changes.

A method with an int return type will return an int, and can be used where an int expression can be used. If bin, bar, bat are each a method taking an int and returning an int, you cold have statements like these:

  • int foo = bar (3) * bin (k) + bat (7);
  • int frob = bar (3) * m + (bat (bin (8));

A method returning a boolean can be used where a boolean expression can be used:

 public static boolean isEnglishLetter (char x) { return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'); } 

You can use it in an if:

 char choice = scan.next ().charAt(0); if (isEnglishLetter (choice)) { ... } 

You can assign it to another boolean:

 boolean goodAnswer = isEnglishLetter (choice); 

So, you use the result returned by the uess method to update the value of correct or not update it.

"... I'm not sure how to write it and use the for loop to count whether the question was right/wrong then count. This includes those guessed correctly on the first try, and those changed to be correct after an initial incorrect response. ..."

Use a record, or a class, to contain each question and answer.

record QA(String q, String a) { } 

And, a Map to contain whether it was answered correctly or not.

Map<QA, Boolean> map = new LinkedHashMap<>(); map.put(new QA("What types of animal(s) can't vomit?", "Rodents"), false); map.put(new QA("What is the only mammal capable of flight?", "Bats"), false); map.put(new QA("What mammal has the most powerful bite", "Hippos"), false); map.put(new QA("Where is the only place that dogs have sweat glands?", "paws"), false); map.put(new QA("What is a male duck called?", "drake"), false); 

Then, traverse map.

Scanner in = new Scanner(System.in); String s1 = "Try again!", s2 = "Sorry! Answer is incorrect. Time for the next question!", s3 = "Good job, you got the correct answer!", s4 = s3 + " Let's move onto the next question"; QA qa; String s; for (Map.Entry<QA, Boolean> e : map.entrySet()) { qa = e.getKey(); System.out.println(qa.q); s = in.nextLine(); if (s.equalsIgnoreCase(qa.a)) { e.setValue(true); System.out.println(s3); } else { System.out.println(s1); s = in.nextLine(); if (s.equalsIgnoreCase(qa.a)) { e.setValue(true); System.out.println(s4); } else System.out.println(s2); } } 

"... at the end of the game we have to count how many questions they got wrong. ..."

I'm using your pseudo-code here.
Count the number of map entries, with a true value.

int correct = 0; for (boolean v : map.values()) if (v) correct++; 

Or, with a stream.

int correct = (int) map.values().stream().filter(x -> x).count(); 

Here is an example output.

What types of animal(s) can't vomit? abc Try again! 123 Sorry! Answer is incorrect. Time for the next question! What is the only mammal capable of flight? Bats Good job, you got the correct answer! What mammal has the most powerful bite Hippos Good job, you got the correct answer! Where is the only place that dogs have sweat glands? paws Good job, you got the correct answer! What is a male duck called? abc Try again! 123 Sorry! Answer is incorrect. Time for the next question! 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like