gpt4 book ai didi

java - 大海捞针(用户输入)(数组)

转载 作者:行者123 更新时间:2023-11-30 06:52:55 25 4
gpt4 key购买 nike

我正在尝试创建一个程序来确定是否在数组中找到用户输入。

然后我要输出整数在数组中的位置。

看起来我的程序没有从我的主程序中提取任何内容。

这是程序:

public static int returnIndex(int[ ] haystack, int needle) {    
for (int n : haystack) {
if (haystack[needle] == n ) {
} else {
System.out.println("Element not found in array");
System.exit(0);
}
}
return needle;
}

public static void main(String[] args) {
int[] haystack = { 4,5,6,7,12,13,15,16,22,66,99,643 };
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number in the array: ");
int needle = sc.nextInt();
}
}

最佳答案

您的循环方式错误。

使用计数 for 循环

for (int index=0; index haystack.length; index++) {
...

相反!然后,将 haystack[index]needle 进行比较,并在匹配时返回 index

请注意:实际上,像在问题中那样使用“for every”循环样式是一种很好的做法 - 这应该是编写循环来迭代数组/集合的项目时的“第一个”想法。但有时您只需要知道 index;那么计数就是正确的选择。

关于java - 大海捞针(用户输入)(数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42408021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com