Alberto 和 devReddit 建议的字符串解析选项很好 (+1)。
我想建议将数据重组为a JSON array:
[
{
"question":"Question A ?",
"options": [
"choicesA-1",
"choicesA-2",
"choicesA-3",
"choicesA-4"
],
"selectedIndex":-1,
"correctIndex":1
},
{
"question":"Question B ?",
"options": [
"choicesB-1",
"choicesB-2",
"choicesB-3",
"choicesB-4"
],
"selectedIndex":-1,
"correctIndex":2
},
{
"question":"Question C ?",
"options": [
"choicesC-1",
"choicesC-2",
"choicesC-3",
"choicesC-4"
],
"selectedIndex":-1,
"correctIndex":3
}
]
如果你将它保存在一个新的草图文件夹中questionnaire.json 你可以加载它并解析(以及检查)这样的答案:
// stores currently loaded questions
JSONArray questions;
// the index of the current question
int currentQuestionIndex = 0;
// the questionnaire data at this index (question, options, correct answer(as index), selected answer(as index))
JSONObject currentQuestionData;
void setup() {
size(400, 400);
// load data
try {
questions = loadJSONArray("questionnaire.json");
}
catch(Exception e) {
println("error loading JSON data");
e.printStackTrace();
exit();
}
}
void draw() {
// get the current question data
currentQuestionData = questions.getJSONObject(currentQuestionIndex);
// access the choices associated with this question
JSONArray currentQuestionOptions = currentQuestionData.getJSONArray("options");
background(0);
// render the question
text(currentQuestionData.getString("question"), 10, 15);
// ...and the choices
for (int i = 0; i < currentQuestionOptions.size(); i++) {
text(currentQuestionOptions.getString(i), 10, 35 + (20 * i));
}
// testing view:
// render user selected index
text("selected: " + currentQuestionData.getInt("selectedIndex"), 10, 120);
// render correct index (and choice text)
text("correct: " + currentQuestionData.getInt("correctIndex") + " = " + currentQuestionOptions.getString(currentQuestionData.getInt("correctIndex")), 10, 150);
// render match condition (result)
text("match: " + (currentQuestionData.getInt("selectedIndex") == currentQuestionData.getInt("correctIndex")), 10, 180);
}
void keyPressed() {
// control question with left/right keys
if (keyCode == LEFT && currentQuestionIndex > 0) currentQuestionIndex--;
if (keyCode == RIGHT && currentQuestionIndex < questions.size() - 1) currentQuestionIndex++;
// set user answers on 1,2,3,4 keys
if (key == '1') currentQuestionData.setInt("selectedIndex", 0);
if (key == '2') currentQuestionData.setInt("selectedIndex", 1);
if (key == '3') currentQuestionData.setInt("selectedIndex", 2);
if (key == '4') currentQuestionData.setInt("selectedIndex", 3);
}
这是相当多的代码,因为除了展示如何解析和呈现问题/选项之外,它还演示了如何使用左/右键测试问题以及使用 1,2 的测试箭头, 3,4 键。希望 cmets 说明了功能。
存储用户选择索引的决定是可选的,更多的是一个想法。稍后存储测验结果可能很有用(saveJSONArray() 可以提供帮助)。
另一种选择可能是将数据存储为 CSV 表,Processing 可以使用 loadTable() 轻松解析该表。
我个人认为 JSON 格式更灵活,尽管它更冗长:您可以使用具有不同数量选项的树结构/问题等,因为 CSV 表格仅限于表格。
加载/保存字符串时的最后一句话:注意特殊字符。
玩得开心!