I am trying to figure out whether it is possible to print out an int ONLY if it is a value in an array of numbers.
For example:
import java.util.Random;
public class arrays {
Random random = new Random();
public void method () {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int j = random.nextInt(20);
if() {
System.out.println("It is in the array.");
} else {
System.out.println("It is not in the array.");
}
}
}
What I am not sure about is what you would put in the parentheses after the "if" in order for the System to print "It is in the array" ONLY if j is between 1 and 9.
Thanks!
Answer
import java.util.Random;
public class arrays {
Random random = new Random();
public void method () {
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int j = random.nextInt(20);
if(Arrays.asList(numbers).contains(j)) {
System.out.println("It is in the array.");
} else {
System.out.println("It is not in the array.");
}
}
}
No comments:
Post a Comment