Hi, How do i write a statement that checks the return value of a method in java. I have to do a conditional action based on the return value of true or false.
How do i put this in an If statement and a while loop.
Thanks
Printable View
Hi, How do i write a statement that checks the return value of a method in java. I have to do a conditional action based on the return value of true or false.
How do i put this in an If statement and a while loop.
Thanks
Here's a small example: filling an array with unique numbers.
Code:import java.util.*;
public class LoopTesting {
public static void main(String[] args) {
Random rand = new Random();
int seed = 20;
int count = 0;
int[] vals = new int[10];
// Initialize elements with -1 to avoid value of zero.
Arrays.fill(vals, -1);
// Fill the vals array with unique numbers [0 - 19].
while(count < vals.length) {
int next = rand.nextInt(seed);
if(isUnique(next, vals))
vals[count++] = next;
}
System.out.printf("vals = %s%n", Arrays.toString(vals));
}
private static boolean isUnique(int n, int[] array) {
for(int j = 0; j < array.length; j++) {
if(array[j] == n)
return false;
}
return true;
}
}