我有一个任务来创建一个 int 数组,该数组在另一种方法中搜索用户输入的 int 值,然后显示该元素在数组中的索引。我让该部分工作得很好,我个人选择将数组中的元素设置为 1 - 10 之间的随机值。如果给定的情况,我还需要让程序显示一条消息(“在数组中找不到元素”)数字不在数组中。我似乎无法让这部分正常工作,希望我能在这里得到一些建议。
import java.util.Scanner;
public class NeedleInHaystack {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please provide an Integer for the needle: ");
int needle = scan.nextInt();
int[] haystack = new int[10];
System.out.println("The array being used is: ");
for (int i = 0; i < 10; i++) {
int j = (int) (Math.random() * 9 + 1);
haystack[i] = j;
System.out.print(haystack[i] + " ");
}
returnIndex(haystack, needle);
}
public static int returnIndex(int[] haystack, int needle) {
int index = needle;
System.out.println("\nThe needle is found at index: ");
for (int i = 0; i < haystack.length; i++) {
if (haystack[i] == index) {
System.out.println(i);
}
}
return index;
}
}
该程序是一个hastack 数组中的一个int 针。如果输入值不存在于随机数组中,使程序“优雅”结束的最佳方法是什么?
作业的措辞如下: “使用一个方法创建一个 Java 程序,该方法在整数数组中搜索指定的整数值(请参阅下面有关启动方法头的帮助)。如果数组包含指定的整数,则该方法应返回其在数组中的索引。如果没有,该方法应该抛出一个异常,指出“在数组中找不到元素”并正常结束。使用您创建的数组和“针”的用户输入来测试 main 中的方法。”
最佳答案
问题出在 for-loop
中,您正在检查数组中的 needle
但不返回它,而且因为您已经分配了 int index = Needle;
开头,即使needle不在数组中,它也会返回needle
因此,在这种情况下,在开头分配index=0
并迭代数组,如果找到则返回index
,否则返回needle
public static int returnIndex(int[] haystack, int needle) {
int index;
System.out.println("\nThe needle is found at index: ");
for (index = 0; index < haystack.length; index++) {
if (haystack[index] == needle) {
System.out.println("value found at index"+index);
return index;
}
}
System.out.println("The value not found in array");
return needle;;
}
关于java - 大海捞针阵列针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53421474/