gpt4 book ai didi

Java arrayList 添加对象 n 次

转载 作者:行者123 更新时间:2023-12-02 11:15:11 25 4
gpt4 key购买 nike

我正在尝试制作一个链接到 sqlite 数据库的 java 测验,从该数据库获取信息(问题和答案)。每个测验有 n 个问题。一个问题有4个选项。一个问题可以有多个真实问题。所以我的数据库表是:测验(id_测验,测验名称)问题(id_question、问题、#id_quiz)答案(id_answer、状态、答案、#id_question)

因此,我创建了第一个框架来选择我们想要通过的测验,它正在使用一个函数,该函数根据所选测验调用新框架。

我的问题是当我将所选答案与必须选择的真实答案进行比较时。这是我的代码:

public boolean compare(List<Integer> trueAnswer, List<Integer> selected){

if (trueAnswer.equals(selected)){
return true;
} else {
return false;
}

}

第一步是在 jLabel 中获取问题以及该问题的答案:

public List<Answer> showQuestion(int index){
in = fillQuestion(idQ).get(index).getIdQuestion();
jQuestion.setText(fillQuestion(idQ).get(index).getQuestion());
try {
con = DriverManager.getConnection("jdbc:sqlite:myflightdb.db", "", "");
String sql2 = ("select r.id_answer ,r.answer, r.statut from question q, answer r where q.id_question = ? and r.id_question = q.id_question ;");
PreparedStatement psmt2;
psmt2 = con.prepareStatement(sql2);
psmt2.setInt(1, in);
List<Answer> listRep = new ArrayList<Answer>();
rs2 = psmt2.executeQuery();
while(rs2.next()){
int idR = rs2.getInt("id_answer");
String rep = rs2.getString("answer");
String statut = rs2.getString("statut");
Reponse r = new Reponse(idR, rep, statut);
listRep.add(r);
}
return listRep;
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return null;
}

函数 getTrueAnswer 是为了获取问题的真实答案列表而创建的:

public List<Integer> getTrueAnswer(int index){
int idquestion;
idquestion = fillQuestion(idQ).get(index).getIdQuestion();
List<Integer> rep = new ArrayList<Integer>();
try {
con = DriverManager.getConnection("jdbc:sqlite:/Users/gate11/Desktop/MyFlight/myflightdb.db", "", "");
String sql = "select r.id_reponse from Reponse r where r.id_question = ? and r.statut like 'true';";
PreparedStatement psmt = con.prepareStatement(sql);
psmt = con.prepareStatement(sql);
psmt.setInt(1, idquestion);
rs = psmt.executeQuery();
while (rs.next()){
int idTrueAnswer= rs.getInt("id_reponse");
rep.add(idTrueAnswer);
}
//JOptionPane.showMessageDialog(null, Arrays.toString(rep.toArray()), "Selected IDs", JOptionPane.INFORMATION_MESSAGE);

return rep;
} catch (Exception e){
System.out.println(""+e.getMessage());
}
return null;
}

接下来的按钮必须将选定的 jCheckBox 与真实问题进行比较,如果相同,则标记必须为 positif(这样我可以将点添加到结果中),或者如果用户不选择真实问题则添加 0 .

问题是第一次,它正在工作(我制作了 JOptionPanes 来查看列表),所以如果我选择第一个问题,我选择的是 [1],真正的答案是 [2]但在第二个问题中,如果我选择 1,则列表为 [1,1],第三个为 [1,1,1],第四个为 [1,1,1,1] 等...而且我没有任何循环我找不到问题。如果有任何想法,请不要犹豫。P.S:我做了 4 个复选框,因为当我尝试将其添加到这样的 for 循环中时:

for (Answer a:listRep){
JcheckBox mycheck = new JcheckBox();
mycheck.setText(a.getQuestion());
mypanel.add(mycheck);
}

最佳答案

我发现了问题,在组件初始化时必须将itemListener添加到jCheckBoxes中。

关于Java arrayList 添加对象 n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50332657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com