import java.util.Random;
public class Exam { public static void main(String[] args){
Random random = new Random();
int x;
for(int counter=1;
counter<=10;
counter ){
x = 10 random.nextInt(100-10);
System.out.println(x);
}
} }
CodePudding user response:
Test is a given int is odd:
boolean isOdd(int number) {
return number % 2 != 0;
}
Generate only odd numbers:
int getOddRandom(Random random) {
random.nextInt()*2 1;
}
CodePudding user response:
To check if a number is odd in java, you can use num % 2 == 0
This returns true if it's even, false if it's odd. A simple way to isolate an odd number this way is to keep generating numbers until it hits one that matches the condition.
public int getFirstOdd() {
Random rand = new Random();
int max = 10;
int min = 1;
while (true) {
int randomNum = rand.nextInt((max - min) 1) min;
if (randomNum % 2 != 0) {
return randomNum;
}
}
}
If for some reason you want to explicitly only generate 10 numbers, just replace the while loop with a for loop.
public int getFirstOdd() {
Random rand = new Random();
int max = 10;
int min = 1;
for (int i = 0; i < 10; i ) {
int num = rand.nextInt((max - min) 1) min;
if (num % 2 != 0) {
return num;
}
}
return -1; //If none of the numbers are odd
}