Wednesday, 9 August 2017

Is it possible to print a number ONLY if it is a value in an array? (Java)




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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...