Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 用于在数组中搜索特定数字的数组程序_Arrays_Algorithm_Search - Fatal编程技术网

Arrays 用于在数组中搜索特定数字的数组程序

Arrays 用于在数组中搜索特定数字的数组程序,arrays,algorithm,search,Arrays,Algorithm,Search,我刚刚学习了Java中的1D数组,我编写了一个代码,从用户那里获取特定数组长度的输入,然后打印用户输入的数据。 之后,用户写入一个数字以检查该数字是否存在于数组中 我有期望的输出,但有一点我不理解逻辑。请引导我 节目如下: //Program to get value from user using array and print all the values import java.util.Scanner; class Array{ public static void main(

我刚刚学习了Java中的1D数组,我编写了一个代码,从用户那里获取特定数组长度的输入,然后打印用户输入的数据。 之后,用户写入一个数字以检查该数字是否存在于数组中

我有期望的输出,但有一点我不理解逻辑。请引导我

节目如下:

    //Program to get value from user using array and print all the values

import java.util.Scanner;
class Array{
public static void main(String args[]){

int[] a = new int[5];
System.out.println("Enter 5 Numbers to Store in a Array");
for(int i = 0; i<a.length; i++){
Scanner in = new Scanner(System.in);
a[i] = in.nextInt();
}

System.out.println("Numbers you Entered are:\n");
for(int i = 0; i<a.length; i++){
System.out.println(a[i]);
}

System.out.println("Check if the number is present in the array or not:");
Scanner ing = new Scanner(System.in);
int input = ing.nextInt();

**if(input == a[4]**){
System.out.println("Number is found");
}
else{
System.out.println("Not Found");
}

}
}

我想知道为什么数组中的数字大小是a[4],因为我的数组大小是a[5]

因为数组是基于零的索引,所以您为值80找到的位置是4


请参考此[

,因为数组是基于零的索引,所以您为值80找到的位置是4


请参考此[

数组从索引0开始,如果数组长度为5,则索引为0,1,2,3,4。您想检查数组中是否有数字,但只检查一个索引是否正常?@OmarAldakar抱歉,我刚刚意识到我的逻辑错误。感谢您的回答。a[4]表示它只打印第5个位置。我已经输入了第5个位置的80。@OmarAldakar我可以使用for循环遍历每个元素,然后打印所需的数字吗?如下所示:for(int i=0;iYes但不是这样,您需要存储在一个布尔值中,以知道您是否看到循环末尾的数字。例如:布尔值x=false;对于(…){if(…){x=true}},则在循环末尾执行if(x){print('yes my number')}else print('no number…'))。否则,您将为列表中不是您的inputAn数组的每个数字打印not found。如果您的数组长度为5,则从索引0开始。索引为0,1,2,3,4。您想检查数组中是否有数字,但只检查一个索引是否正常?@OmarAldakar抱歉,我刚刚意识到我的逻辑错误。谢谢您的回答。a[4]表示它只打印第5个位置。我已经输入了第5个位置的80。@OmarAldakar我可以使用for循环遍历每个元素,然后打印所需的数字吗?如下所示:for(int i=0;iYes但不是这样,您需要存储在一个布尔值中,以知道您是否看到循环末尾的数字。例如:布尔值x=false;对于(…){if(…){x=true}},则在循环末尾执行if(x){print('yes my number')}else print('no number…'))。否则,您将无法打印列表中不是您输入的每个数字。我刚刚意识到我的错误逻辑。谢谢您的回答。如果它帮助了您,请更新投票或接受它。我刚刚意识到我的错误逻辑。谢谢您的回答。如果它帮助了您,请更新投票或接受它
    Enter 5 Numbers to Store in an Array
56
45
78
79
80
Numbers you Entered are:

56
45
78
79
80
Check if the number is present in the array or not:
80
Number is found