如何编写Java方法统计问答游戏中的正确答题数?
解决Java问答游戏的答题统计与方法实现问题
原代码存在的核心问题
- 方法不能嵌套定义(
guess和correct方法不能放在main方法内部) - 重复声明
input变量,且提前读取输入的逻辑错误 guess方法的循环逻辑混乱,重复调用nextLine()导致多读取用户输入,且未返回答题结果用于统计- 缺少正确答题数的统计逻辑实现
修正后的完整代码
import java.util.Scanner; public class AnimalTriviaGame { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int correctCount = 0; // 游戏介绍 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."); // 逐个提问并统计正确数 if (askQuestion("What types of animal(s) can't vomit?", "Rodents", scan)) { correctCount++; } if (askQuestion("What is the only mammal capable of flight?", "Bats", scan)) { correctCount++; } if (askQuestion("What mammal has the most powerful bite?", "Hippos", scan)) { correctCount++; } if (askQuestion("Where is the only place that dogs have sweat glands?", "paws", scan)) { correctCount++; } if (askQuestion("What is a male duck called?", "drake", scan)) { correctCount++; } // 输出最终统计结果 System.out.println("\nGame Over!"); System.out.println("You got " + correctCount + " out of 5 questions correct."); scan.close(); } // 处理单个问题的答题逻辑,返回是否答对 private static boolean askQuestion(String question, String correctAnswer, Scanner scanner) { System.out.println("\n" + question); // 给用户2次答题机会 for (int attempt = 1; attempt <= 2; attempt++) { String userInput = scanner.nextLine().trim(); if (userInput.equalsIgnoreCase(correctAnswer)) { System.out.println("Good job, you got the correct answer!"); return true; // 答对直接返回true,结束当前问题 } else { if (attempt == 1) { System.out.println("Try again!"); } else { System.out.println("Sorry! Answer is incorrect. The correct answer is: " + correctAnswer); } } } return false; // 两次都答错返回false } }
关键逻辑说明
- 方法封装:把单个问题的答题逻辑封装到
askQuestion方法中,参数包含问题文本、正确答案和Scanner,返回布尔值表示是否答对,便于统计正确数。 - 答题循环:用
for循环控制2次答题机会,第一次答错提示重试,第二次答错直接给出正确答案。 - 统计逻辑:在
main方法中初始化计数器correctCount,每调用一次askQuestion就根据返回值更新计数器,最后输出统计结果。 - 输入处理:用
trim()去除用户输入的首尾空格,equalsIgnoreCase()忽略大小写判断,提升用户体验。
内容的提问来源于stack exchange,提问作者jiayou
相关产品推荐
相关产品推荐

