2

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!

JCS
  • 39
  • 5

4 Answers4

5

Use the java.util.Arrays utility class. It can convert your array to a list allowing you to use the contains method or it has a binary search allowing you to find the index of your number, or -1 if it is not in the array.

import java.util.Arrays;
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( Arrays.binarySearch(numbers, j) != -1 ) {
            System.out.println("It is in the array.");
        } else {
            System.out.println("It is not in the array.");
        }
    }
}
Sam
  • 101
  • 4
4
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.");
        }
    }
}
Lukas Rotter
  • 4,158
  • 1
  • 15
  • 35
  • I tried to do this but no matter what number j is (I added "System.out.println(j);" so I can tell what j is), I get "It is not in the array" even when it is. Any idea why? Thanks. – JCS Jul 26 '15 at 17:31
3
Arrays.asList(numbers).contains(j)

or

ArrayUtils.contains( numbers, j )
Vishnu
  • 11,614
  • 6
  • 51
  • 90
1

Since your array is sorted, you can use Arrays.binarySearch which returns index of the element if it is present in the array, otherwise returns -1.

if(Arrays.binarySearch(numbers,j) != -1){
     system.out.println("It is in the array.");
} else {
     system.out.println("It is not in the array.");
}

Just a faster way to search and you also don't need to convert your array to list.

Karthik
  • 4,950
  • 6
  • 35
  • 65