Java Algorithms How to - Generate a random -1 or 1








Question

We would like to know how to generate a random -1 or 1.

Answer

/*from   ww  w  . j  av a 2s . c  o m*/

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
      System.out.println(randomOneOrMinusOne());
    }
  }
  static int randomOneOrMinusOne() {
    Random rand = new Random();
    if (rand.nextBoolean())
      return 1;
    else
      return -1;
  }
}

The code above generates the following result.