第一次发帖,希望不会搞砸。
我的任务是让用户输入一个包含 10 个整数的数组,然后单独输入另一个整数,让程序检索该数字(如果该数字在数组中),否则给出错误。
我无法将输入的整数与数组中的整数进行比较。
这是我的代码的一部分,其余部分如下:
try{
System.out.print("Please enter 10 integers to store in an array and then press enter: ");
for(int index = 0; index < numbers.length; index++)
numbers[index] = input.nextInt();
if(numbers.length==10){ //method doesnt work properly if you input over 10 integers, only if you input less
System.out.print("Thanks for entering 10 integers. Now input an integer to check: ");
int compare = input.nextInt();
if(numbers[index] == compare){ //this is where the error is I believe
System.out.print(compare); //here too
}
提前谢谢您!
最佳答案
如果您使用java-8 ,您可以使用 IntStream
boolean contained = IntStream.of(inputtedNumbers)
.anyMatch(x -> x == numberToSearch);
关于java - 检查数组中的特定整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35819755/