【问题标题】:Array Program for Searching a Specific number in Array在数组中查找特定数字的数组程序
【发布时间】:2020-06-07 18:30:06
【问题描述】:

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

我有想要的输出,但在一个地方我无法理解逻辑。请指导我。

这是程序:

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

}
}

和输出:

    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

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

【问题讨论】:

  • 如果您有一个长度为 5 的数组,则数组从索引 0 si 开始,索引为 0,1,2,3,4。您想检查一个数字是否在数组中,但您只检查一个索引是否正常?
  • @OmarAldakar 抱歉,我刚刚意识到我的逻辑是错误的。谢谢回答。 a[4] 表示它只打印第 5 个位置。我已经进入了第 5 位的 80。
  • @OmarAldakar 我可以使用 for 循环遍历每个元素,然后打印所需的数字吗?像这样: for(int i = 0; i
  • 是的,但不是这样,你需要存储在一个布尔值中才能知道你是否看到了循环末尾的数字。
  • 例如:boolean x = false; for(...){if(...){x = true}} 然后在循环结束时执行 if(x) {print('yes my number')} else print('no number .. .')。否则,对于不是您输入的列表中的每个数字,您将打印 not found

标签: arrays algorithm search


【解决方案1】:

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

请参考这个[https://softwareengineering.stackexchange.com/questions/110804/why-are-zero-based-arrays-the-norm]

【讨论】:

  • 我刚刚意识到我的逻辑错误。谢谢你的回答
  • 好的,如果对你有帮助,请点赞或采纳
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 2022-11-01
  • 1970-01-01
  • 2018-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多