dimanche 27 novembre 2016

Why does one random int become the same as another random int after I specifically prevent this? (JAVA)

In my program, two random numbers are generated. One of them (rbvalue) is between 0 and 8. The other, loadG4, is between 0 and 9. If rbvalue is ever == as loadG4, it'll be set to 9. This way, the two numbers can never be equal. For some reason, the code is flawed after the first time a button is clicked (program loops after each button click). In the code there may be excess information not relevant, I am putting it in anyway in case in clashes with the random generation and comparison that we are focusing on. Here is the code:

Random random = new Random();
int rbselector = random.nextInt(4);    //These three are declared outside of onCreate.
int loadG4 = random.nextInt(10);


for(int allrbA=0; allrbA<4; allrbA++) {
                int rbvalue = random.nextInt(9);
                if (rbvalue == loadG4) {
                    rbvalue=9;
                }
                selectrb[allrbA].setText(""+rbvalue);
            }
            selectrb[rbselector].setText(""+ loadG4);


                for (int allrbA = 0; allrbA < 4; allrbA++) {
                selectrb[allrbA].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                            Button clicked = (Button) v;
                            String clickVal = (String) clicked.getText();
                            int finalClick = Integer.valueOf(clickVal);

                            if (finalClick == loadG4) {
                                score++;
                                for (int allrbA = 0; allrbA < 4; allrbA++) {
                                    int rbvalue = random.nextInt(9);
                                    loadG4 = random.nextInt(10);
                                    if (rbvalue == loadG4) {
                                        rbvalue=9;
                                    }
                                    selectrb[allrbA].setText("" + rbvalue);
                                }
                                number.setText("" + loadG4);
                                rbselector = random.nextInt(4);
                                selectrb[rbselector].setText("" + loadG4);
                            }
                    }
                });
                }

Many thanks in advance.




Aucun commentaire:

Enregistrer un commentaire