答案:通過定義Question類和List存儲問題與答案,使用Scanner獲取用戶輸入并驗證,最后輸出或保存結(jié)果,實現(xiàn)一個結(jié)構(gòu)清晰、交互友好的Java控制臺問卷調(diào)查系統(tǒng)。
在Java中實現(xiàn)一個小型問卷調(diào)查,關(guān)鍵在于結(jié)構(gòu)清晰、交互友好。你可以用控制臺程序完成基本功能,不需要圖形界面也能做到邏輯完整、用戶易操作。
先定義問題和選項。每個問題可以封裝成一個類,便于管理:
class Question { String text; String[] options; <pre class='brush:java;toolbar:false;'>public Question(String text, String[] options) { this.text = text; this.options = options; }
}
然后創(chuàng)建一個問題列表:
立即學(xué)習(xí)“Java免費學(xué)習(xí)筆記(深入)”;
List<Question> questions = new ArrayList<>(); questions.add(new Question("你對當(dāng)前服務(wù)滿意嗎?", new String[]{"非常滿意", "滿意", "一般", "不滿意"})); questions.add(new Question("你多久使用一次該產(chǎn)品?", new String[]{"每天", "每周幾次", "每月幾次", "很少"}));
使用Scanner讀取用戶輸入,逐個展示問題并記錄答案:
采風(fēng)問卷是一款全新體驗的調(diào)查問卷、表單、投票、評測的調(diào)研平臺,新奇的交互形式,漂亮的作品,讓客戶眼前一亮,讓創(chuàng)作者獲得更多的回復(fù)。
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("請選擇(輸入數(shù)字):");</p><pre class='brush:java;toolbar:false;'>while (!scanner.hasNextInt()) { System.out.print("請輸入有效數(shù)字:"); scanner.next(); } int choice = scanner.nextInt() - 1; if (choice >= 0 && choice < q.options.length) { answers.add(choice); } else { System.out.println("選擇無效,跳過此題。"); answers.add(-1); // 表示未作答 }
}
收集完數(shù)據(jù)后,可以簡單輸出統(tǒng)計結(jié)果或?qū)懭胛募?/p>
System.out.println("\n--- 調(diào)查結(jié)果 ---");
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("無法保存結(jié)果。"); }
基本上就這些。不復(fù)雜但容易忽略的是輸入驗證和用戶體驗。加點提示、防止崩潰、讓流程順暢,小問卷也能很實用。
以上就是如何在Java中實現(xiàn)小型問卷調(diào)查的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
每個人都需要一臺速度更快、更穩(wěn)定的 PC。隨著時間的推移,垃圾文件、舊注冊表數(shù)據(jù)和不必要的后臺進程會占用資源并降低性能。幸運的是,許多工具可以讓 Windows 保持平穩(wěn)運行。
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號