0
即時通訊開發一個簡單的測驗,其中我有50個問題存儲..我的問題是,我不能隨機化的問題,它應該隨機每次用戶會玩,只有10個問題要顯示...請幫助我...我使用這個An efficient way to shuffle a JSON array in java?完成但它不工作!!!!!非常感謝你的幫助!如何隨機測驗在測驗中的問題每次用戶使用json數組在玩android
public class Question1 extends Activity {
Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;
static int index = 50;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question10);
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(1 * 1000);
finish();
loadQuestions();
Intent intent = new Intent(Question1.this,
Question2.class);
Question1.this.startActivity(intent);
} catch (Exception e) {
}
}
};
thread.start();
}
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e) {
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray shuffleJsonArray (JSONArray quesList) throws JSONException {
// Implementing Fisher–Yates shuffle
Random rnd = new Random();
for (int i = quesList.length() - 1; i >= 0; i--)
{
int j = rnd.nextInt(i + 1);
// Simple swap
Object object = quesList.get(j);
quesList.put(j, quesList.get(i));
quesList.put(i, object);
}
return quesList;
}
shuffleJsonArray() – Naveen 2013-02-22 04:38:53
您可以隨機生成問題編號並將它們保存在數組中,然後使用該數組隨機顯示問題? – Shiv 2013-02-22 04:41:11
@Shiv是的。每次用戶開始遊戲時都必須隨機顯示問題。 – user2079544 2013-02-22 04:47:58