答案:通过定义Question类和List存储问题与答案,使用Scanner获取用户输入并验证,最后输出或保存结果,实现一个结构清晰、交互友好的Java控制台问卷调查系统。

在Java中实现一个小型问卷调查,关键在于结构清晰、交互友好。你可以用控制台程序完成基本功能,不需要图形界面也能做到逻辑完整、用户易操作。
先定义问题和选项。每个问题可以封装成一个类,便于管理:
class Question {
String text;
String[] options;
<pre class='brush:java;toolbar:false;'>public Question(String text, String[] options) {
this.text = text;
this.options = options;
}}
然后创建一个问题列表:
立即学习“Java免费学习笔记(深入)”;
List<Question> questions = new ArrayList<>();
questions.add(new Question("你对当前服务满意吗?",
new String[]{"非常满意", "满意", "一般", "不满意"}));
questions.add(new Question("你多久使用一次该产品?",
new String[]{"每天", "每周几次", "每月几次", "很少"}));
使用Scanner读取用户输入,逐个展示问题并记录答案:
Scanner scanner = new Scanner(System.in);
List<Integer> answers = new ArrayList<>();
<p>for (int i = 0; i < questions.size(); i++) {
Question q = questions.get(i);
System.out.println((i + 1) + ". " + q.text);
for (int j = 0; j < q.options.length; j++) {
System.out.println(" " + (j + 1) + ". " + q.options[j]);
}
System.out.print("请选择(输入数字):");</p><pre class='brush:java;toolbar:false;'>while (!scanner.hasNextInt()) {
System.out.print("请输入有效数字:");
scanner.next();
}
int choice = scanner.nextInt() - 1;
if (choice >= 0 && choice < q.options.length) {
answers.add(choice);
} else {
System.out.println("选择无效,跳过此题。");
answers.add(-1); // 表示未作答
}}
收集完数据后,可以简单输出统计结果或写入文件:
System.out.println("\n--- 调查结果 ---");
for (int i = 0; i < questions.size(); i++) {
System.out.println((i + 1) + ". " + questions.get(i).text);
int answerIndex = answers.get(i);
if (answerIndex != -1) {
System.out.println(" 你的选择:" +
questions.get(i).options[answerIndex]);
} else {
System.out.println(" 未作答");
}
}
如果想持久化,可用PrintWriter写入文本文件:
try (PrintWriter out = new PrintWriter("survey_result.txt")) {
for (int i = 0; i < questions.size(); i++) {
out.println(questions.get(i).text + " -> " +
(answers.get(i) == -1 ? "N/A" :
questions.get(i).options[answers.get(i)]));
}
} catch (FileNotFoundException e) {
System.out.println("无法保存结果。");
}
基本上就这些。不复杂但容易忽略的是输入验证和用户体验。加点提示、防止崩溃、让流程顺畅,小问卷也能很实用。
以上就是如何在Java中实现小型问卷调查的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号