1

I'm learning how to do a simple quiz game. In the game, a random number is generated to make a new question appear (there's a switch where each case is associated with one different question) after the click. Each question have just one right answer and the next question is shown after any button is clicked (doesn't matter if the person clicked in the right button or not). But I'm trying to make the buttons appear in a random way too... I tried this:

    final Random rng = new Random();
    final List<Integer> generated = new ArrayList<Integer>();

        while(true){

            if(generated.size()!=3) {

                Integer nxt = rng.nextInt(3) + 1;

                if (!generated.contains(nxt))
                {
                    generated.add(nxt);

                    textView1 = (TextView) findViewById(R.id.textView1);
                    switch (nxt) {
                    case 1: 
                        textView1.setText("Question 1");

                        btn1.setText("Right answer");
                        btn2.setText("Wrong 1");
                        btn3.setText("Wrong 2");
                        btn4.setText("Wrong 3");


                        break;
                    case 2: 
                        textView1.setText("Question 2");

                        btn1.setText("Right answer");
                        btn2.setText("Wrong 1");
                        btn3.setText("Wrong 2");
                        btn4.setText("Wrong 3");

                        break;
                    case 3: 
                        textView1.setText("Question 3");

                        btn1.setText("Right answer");
                        btn2.setText("Wrong 1");
                        btn3.setText("Wrong 2");
                        btn4.setText("Wrong 3");

                        break;
                }

                break;
            }
        }

    }

I put this code in the onCreate (to the question already appears when the user enter this activity questions) and in the onClick of button 1 (for another question appears when the button is clicked.) The order of all the 4 answers (4 buttons) should be randomized. What is the best way to do something like that?

2 Answers2

1

You might want to create a 'QuestionInfo' class which holds the question, answers, and any other required data. Then you can create a collection (array or list) of 'QuestionInfo' objects which will make it very easy to select a random question and populate your UI. No giant switch statement required.

Tyler MacDonell
  • 2,609
  • 18
  • 27
  • I was starting to think "this code gonna be huge". Thank you. I'll learn to work with this. –  Mar 04 '13 at 04:02
-1

Creating an array will helps randomizing your questions.

joanne933
  • 11
  • 6