Jugjin
Jugjin

Reputation: 57

How to make random check Java?

I have a quiz and when user clicks on "50/50 " button there should left only correct answer and one random incorrect answer.

int a=0;
            while(a!=2){
                int random = new Random().nextInt(4)+1 ;

                if(random%4==0) {
                    if(answer4.getText()!=mAnswearFi){
                        answer4.setText("");
                        answer4.setEnabled(false);
                        a++;
                    }

                }
                if(random%3==0) {
                    if(answer3.getText()!=mAnswearFi){
                        answer3.setText("");
                        answer3.setEnabled(false);
                        a++;
                    }
                }
                if(random%2==0) {
                    if(answer2.getText()!=mAnswearFi){
                        answer2.setText("");
                        answer2.setEnabled(false);
                        a++;
                    }

                }
                 if (random%1==0) {
                    if(answer1.getText()!=mAnswearFi){
                        answer1.setText("");
                        answer1.setEnabled(false);
                        a++;
                    }

                }

            }

( mAnswerFi here - it is a correct answer ; answer1,2,3,4 - buttons that will be pressed.) Sometimes it lefts 3 answers or crashes without any changing ( text on buttons doesnt disappear on all 4 buttons) but i need 2 answers to be left. What should i do? Thanks in advance!

Upvotes: 0

Views: 65

Answers (1)

mangusta
mangusta

Reputation: 3544

You better keep your buttons in the array. Also the disabled buttons need to be tracked in order to disable exactly 2 distinct buttons, otherwise the counter is incremented even if the button has already been disabled:

            Random rand = new Random(); //initialize generator here only once
            Set<Integer> disabledButtons = new HashSet<Integer>();
            int a=0;
            Button[] buttons = new Button[4]; //keep buttons here
            while(a<2)
            {
                int random = rand.nextInt(4);

                if(buttons[random].getText()!=mAnswerFi && !disabledButtons.contains(random)) {
                        buttons[random].setText("");
                        buttons[random].setEnabled(false);
                        disabledButtons.add(random);
                        a++;
                }

            }//end while

Upvotes: 1

Related Questions