0

using iOS I sometimes like to call 2 functions at random a button press for example, I would use; So sometimes, the user would get (1) the other time (2) etc.

if (arc4random() % 2 == 0) {

// Do one thing (1)

        } else {

       // Do something else(2)

        }
    }

How would I do this within Eclipse/java? In otherwords, what is the same statement but in a Java language?

user3355723
  • 235
  • 2
  • 11
  • 1
    Do a web search for "random java".... – nneonneo Jun 16 '14 at 22:10
  • possible duplicate of [http://stackoverflow.com/questions/363681/...](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) and [http://stackoverflow.com/questions/901689/...](http://stackoverflow.com/questions/901689/java-generate-random-number-1-0-1) and so many others. – alex Jun 16 '14 at 23:28

1 Answers1

2

Use the Java Random class. This would give you either 1 or 2:

Random rand = new Random();
int n = rand.nextInt(2) + 1;

nextInt(n) gives you a random number from 0 to n-1 (inclusive). So you have to add 1 to the result.

Edwin Torres
  • 2,774
  • 1
  • 13
  • 15