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!

1

4 Answers 4

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.");
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.");
        }
    }
}

1 Comment

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.
3
Arrays.asList(numbers).contains(j)

or

ArrayUtils.contains( numbers, j )

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.