0

I really want some Java that randomizes from 1-2 and all that I came up with (Doesn't work either) is:

random.math (int.1+2)

Might actually look stupid to an expert but yeah

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Xilog
  • 1
  • 2

2 Answers2

1

Since you're just wanting to flip between two integers, You can utilize a ternary operator and the Math.random() static method to achieve the desired results:

Math.random() >= 0.5 ? 2 : 1
Darth Android
  • 3,437
  • 18
  • 19
  • Question seems to indicate that an `int` value is desired, and if you cast that to `int`, you'll only ever get the number `1`, not a random mixture of 1's and 2's. – Andreas Mar 17 '16 at 18:19
  • Yeah my poor little brain breaks from Jav – Xilog Mar 17 '16 at 18:22
  • @Andreas Good point, updated to reflect the desired integer results. – Darth Android Mar 17 '16 at 18:26
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/11672895) – Toby Speight Mar 17 '16 at 18:31
  • @TobySpeight I'm confused, how does this not provide an answer to the question? OP was asking for a java expression that randomly returned either `1` or `2`. – Darth Android Mar 17 '16 at 18:36
  • At the time of my review, it was a comment asking OP whether a code snippet works. Now it has been rephrased as an answer, it's worthy of an upvote (and has one from me). – Toby Speight Mar 18 '16 at 09:15
  • BTW, a related (but far from idiomatic) alternative: `(int)(Math.random() + 1.5)`. The sum is equally likely to fall in the range [1.5, 2.0) or the range [2.0, 2.5), which, after truncation, yield 1 and 2 respectively. – Toby Speight Mar 18 '16 at 09:20
0

The easiest would be to use the Random.nextInt(int n) method, which will generate an integer between 0 and n-1, inclusive.

Here is an example:

Random rnd = new Random();
for (int i = 0; i < 20; i++) {
    int number = rnd.nextInt(2) + 1;
    System.out.print(number + " ");
}

OUTPUT

1 2 1 1 2 1 1 2 2 1 2 2 2 2 1 2 2 2 1 1 
Andreas
  • 154,647
  • 11
  • 152
  • 247