0

嘿,伙计们,我正在开发一个测验,其中存储了 50 个问题,然后我希望它只显示 10 个问题..问题是随机显示的..但我的问题是应该在测验中显示 10 个问题。请帮助我...帮助真的很感激..

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 getQuesList()throws JSONException{

      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;


}
4

2 回答 2

2

由于您希望在每个测验中都有 10 个动态问题,因此您可以使用 ArrayListCollections.shuffle(YourList)打乱,并从该打乱列表中取出前 10 个。

但是,当您拥有 JSONArray 时,您必须对其进行迭代并准备 ArrayList,这样您就可以使用shuffle().

更新:

参考 ogzd 的答案,这样你就会有问题List<JsonObject>现在你只需调用我上面提到的 shuffle 方法:

Collections.shuffle(questions);

现在,它将随机排列问题列表,因此您必须从中复制或获取前 10 个项目。

于 2013-02-22T07:34:45.430 回答
0

尝试:

 List<JsonObject> questions = new ArrayList<JsonObject>();
 int n = Math.min(10, quesList.length());
 for(int i = 0; i < n; i++) {
     JsonObject question = quesList.getJsonObject(i);
     questions.add(question);
 }
于 2013-02-22T07:26:34.567 回答