简体   繁体   中英

Randomize array of questions while reading from text file android

This is a android quiz app code snippet which load the question from text file. I want to shuffle the question and answer after every next click so how can i implement random function ? https://github.com/gitssk/quizfun/blob/master/src/ssk/quizfun/QuizFunActivity.java

https://github.com/gitssk/quizfun/blob/master/res/raw/questions.txt

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

        }


    }







https://github.com/gitssk/quizfun/blob/master/src/ssk/quizfun/QuizFunActivity.java

I will refrain from posting much code because I think you should attempt it on your own. It is seriously not that tough. I will give you an approach though.

You have quesList = quesObj.getJSONArray("Questions"); . So quesList is the list of questions that is a JSONArray . You want to shuffle this. Just do this:

  1. Get the length of the quesList array. Let's call it len .
  2. Create a simple arrayList called quesOrder containing integers 0 to len .

     List<Integer> quesOrder = new ArrayList<>(); for (int i = 0; i <= len; i++) { quesOrder.add(i); } 

Once you have the quesOrder array. Just do Collections.shuffle(quesOrder); . Now when you get questions from your quesList array, just get the index from quesOrder list. And you will have a randomized selection. Put it together in a function for convenience.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM