17370845950

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

在Java中实现一个小型问卷调查,关键在于结构清晰、交互友好。你可以用控制台程序完成基本功能,不需要图形界面也能做到逻辑完整、用户易操作。

设计问卷结构

先定义问题和选项。每个问题可以封装成一个类,便于管理:

class Question {
    String text;
    String[] options;
public Question(String text, String[] options) {
    this.text = text;
    this.options = options;
}

}

然后创建一个问题列表:

List questions = new ArrayList<>();
questions.add(new Question("你对当前服务满意吗?", 
    new String[]{"非常满意", "满意", "一般", "不满意"}));
questions.add(new Question("你多久使用一次该产品?", 
    new String[]{"每天", "每周几次", "每月几次", "很少"}));

实现用户交互

使用Scanner读取用户输入,逐个展示问题并记录答案:

Scanner scanner = new Scanner(System.in);
List answers = new ArrayList<>();

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("请选择(输入数字):");

while (!scanner.hasNextInt()) {
    System.out.print("请输入有效数字:");
    scanner.next();
}
int choice = scanner.nextInt() - 1;

if (choice >= 0 && choice zuojiankuohaophpcn 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("无法保存结果。");
}

基本上就这些。不复杂但容易忽略的是输入验证和用户体验。加点提示、防止崩溃、让流程顺畅,小问卷也能很实用。