java - 使用 Arraylist contains () 查找给定的整数是否在数组中

标签 java arrays if-statement

检查给定输入是否在数组中时遇到问题。下面只是我编写的示例代码。由于某种原因,无论我输入什么,即使数字在数组中,它也会输出“不好”。任何建议或帮助将不胜感激。

public static void main (String[] args) {
    Scanner input = new Scanner(System.in);
    int array [] = new int[10];
    System.out.println("Please enter the 10 positive integers for BST:"); 
    for (int i = 0 ; i < array.length; i++ ) {
        array[i] = input.nextInt();
    }
    System.out.println("Enter node to delete");
    if (Arrays.asList(array).contains(input.nextInt())){                
        System.out.println("ok");
    } else
        System.out.println("not Okay");
}

最佳答案

Arrays.asList(array)将转换 int[] array进入List<int[]> ,然后List<int[]>#contains将尝试搜索 Integer 。如前所述,它永远找不到它。

解决这个问题的方法:

  • 更改 int[]Integer[] .

  • 创建一个接收 int 的方法并搜索数组中的元素。

(代码不会显示在答案中,因为问题看起来像家庭作业)。

关于java - 使用 Arraylist contains () 查找给定的整数是否在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23392037/

相关文章:

java - 按位提取后从android中的彩色图像中获取灰度图像

java - Cloud Firestore - 无法获取文档计数

java - do-while 循环的范围?

javascript - Ajax请求返回空数组

C 字符数组串联内存转储

c++ - 在 C++ 中返回 C 字符串数组

c# - C#如何检查字符串中重复的字母

javascript - 访问最后一个 if 语句条件结果值

java - 在intellij idea和java语言中使用Stimulsoft

c++ - 翻转逻辑表达式