【问题标题】:Is it possible to print a number ONLY if it is a value in an array? (Java) [duplicate]仅当它是数组中的值时才可以打印数字吗? (Java)[重复]
【发布时间】:2015-10-16 20:19:31
【问题描述】:

我试图弄清楚是否只有当它是数字数组中的值时才可以打印出 int。 例如:

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

我不确定的是,只有当 j 介于 1 和 9 之间时,您才会在“if”之后的括号中放入什么内容,以便系统打印“它在数组中”。

谢谢!

【问题讨论】:

标签: java arrays


【解决方案1】:

使用 java.util.Arrays 实用程序类。它可以将你的数组转换为一个列表,让你可以使用 contains 方法,或者它有一个二进制搜索,让你可以找到你的数字的索引,如果它不在数组中,则为 -1。

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

【讨论】:

    【解决方案2】:
    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.");
            }
        }
    }
    

    【讨论】:

    • 我尝试这样做,但无论 j 是什么数字(我添加了“System.out.println(j);”所以我可以知道 j 是什么),我得到“它不在数组”,即使它是。知道为什么吗?谢谢。
    【解决方案3】:
    Arrays.asList(numbers).contains(j)
    

    ArrayUtils.contains( numbers, j )
    

    【讨论】:

      【解决方案4】:

      由于您的数组已排序,您可以使用Arrays.binarySearch,如果该元素存在于array 中,则返回该元素的索引,否则返回-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.");
      }
      

      只是一种更快的搜索方式,您也无需将array 转换为list

      【讨论】:

        猜你喜欢
        • 2019-02-06
        • 1970-01-01
        • 2015-11-17
        • 1970-01-01
        • 1970-01-01
        • 2023-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多