gpt4 book ai didi

java - 从 SQLite 数据库生成随机输出

转载 作者:行者123 更新时间:2023-12-01 11:37:16 24 4
gpt4 key购买 nike

您好,我目前有一个数据库,其中存储了 5 个问题和答案。我想在应用程序每次运行时随机输出三个问题。我有以下代码,但我的应用程序在加载时崩溃

public List<Question> getAllQuestions() {
List<Question> quesList = new ArrayList<Question>();
int nQuestions = 3; //select COUNT(*) from questions

Random random = new Random();
int id = random.nextInt(nQuestions);

String selectQuery = "SELECT id FROM " + TABLE_QUEST;
dbase=this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Question quest = new Question();
quest.setID(cursor.getInt(0));
quest.setQUESTION(cursor.getString(1));
quest.setANSWER(cursor.getString(2));
quest.setOPTA(cursor.getString(3));
quest.setOPTB(cursor.getString(4));
quest.setOPTC(cursor.getString(5));
quesList.add(quest);
} while (cursor.moveToNext());{
id = random.nextInt(nQuestions);
}
}
// return quest list
return quesList;
}

最佳答案

抱歉,我写这个作为答案,但我没有对问题发表评论的权限,所以我想告诉你,首先,你将永远成为前 3 个随机添加的问题之一问题,因为对于您用作限制的随机 id 3 id = random.nextInt(nQuestions); 而不是 nQuestions (对您来说是 3,您应该使用 questList.size()并对从0到questList.size()的数字执行3次

关于java - 从 SQLite 数据库生成随机输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29848978/

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