Java Program to generate custom random number -1 or 1

Java 8Object Oriented ProgrammingProgramming

To generate custom random number 1 or -1, you need to use nextBoolean(). At first take a loop and create a Random object on each iteration −

for (int i = 0; i < 5; i++) {
   Random rand = new Random();
}

Now, use nextBoolean() to generate 1 on TRUE condition, ekse -1 −

for (int i = 0; i < 5; i++) {
   Random rand = new Random();
   if (rand.nextBoolean())
      System.out.println(1);
   else
      System.out.println(-1);
}

Example

 Live Demo

import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      for (int i = 0; i < 5; i++) {
         Random rand = new Random();
         if (rand.nextBoolean())
            System.out.println(1);
         else
            System.out.println(-1);
      }
   }
}

Output

1
-1
-1
-1
-1
raja
Published on 23-Apr-2019 12:30:28
Advertisements