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