dimanche 20 novembre 2016

How does this code work? (Java)

I have program in which 4 random numbers are set to 4 buttons (one no. for each button). There are two random variables (rbvalue and loadG4). The rbvalue number is different for each button, but the loadG4 value overrides a button's value and replaces it. The idea is, none of the rbvalue numbers are meant to be equal to loadG4, and a part of the program ensures they are never equal. Here's the code:

Random GenerateG4 = new Random();
            int loadG4 = GenerateG4.nextInt(10);
            Random randoms1 = new Random();
            final TextView number = (TextView) findViewById(R.id.number);
            number.setText(""+loadG4);
            for(int allrbA=0; allrbA<4; allrbA++) {
                int rbvalue = randoms1.nextInt(10);
                if (rbvalue==loadG4) rbvalue=9;
                selectrb[allrbA].setText(""+rbvalue);
            }
            selectrb[rbselector].setText(""+loadG4);

The part that makes this work is:

if (rbvalue==loadG4) rbvalue=9;

Simply adding that line of code in did the job. Now out of all numbers generated from 0 to 9, there is only one of which is the value of loadG4. How did that one line do this? I always thought that after if (...) there has to be curly brackets for the actual statements e.g if (...) {System.out.println("...")} Why set rbvalue to 9?

I'd appreciate anyone who could clear this up for me, thank you.




Aucun commentaire:

Enregistrer un commentaire