簡體   English   中英

每次用戶使用android中的json數組玩游戲時如何隨機化測驗中的問題

[英]how to randomize questions in the quiz every time the user play using json array in android

我正在開發一個簡單的測驗,我存儲了50個問題..我的問題是,我無法將問題隨機化,每次用戶播放時都應該隨機化,只有10個問題可以顯示...請幫助我...我使用這種有效的方法來在Java中隨機播放JSON數組? 但是它不起作用!!!!!非常感謝您的幫助!

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;
}

您可以啟動一個循環,隨機生成問題編號並將其保存在數組中,然后使用該數組綁定或顯示問題。這將是隨機的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM