Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
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
Advertisements
