Java Program to generate custom random number -1 or 1



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
Updated on: 2019-07-30T22:30:25+05:30

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements