干草堆中的阵列针

时间:2018-11-21 22:44:42

标签: java arrays

我有一个任务来创建一个int数组,该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中使用您制作的数组以及用户对“针”的输入来测试该方法。”

3 个答案:

答案 0 :(得分:2)

问题在for-loop中,您正在检查数组中的needle但不返回它,而且由于即使在开始时您都分配了int index = 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;;
}

答案 1 :(得分:0)

您可以在设置为true的方法中添加某种boolean标志(如果找到)。如果不是,该标志将保持为假。遍历数组后,可以检查该标志是否为false,如果为false,则可以打印一些错误消息。

public static int returnIndex(int[] haystack, int needle) {

    boolean found = false;

    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);
            found = true;
        }
    }

    if (found) return index;

    else  {

        System.out.println("Not found.");
        return null;

    }


 }

}

答案 2 :(得分:0)

由于应该返回索引而不是指针值,因此一旦找到对象,就应该在for循环内返回。与Deadpool非常相似。

但是当您声明该方法应该在找不到针时抛出异常时,您应该摆脱第二个return语句,而只是抛出异常。

public static int returnIndex(int[] haystack, int needle) {
    System.out.println("\nThe needle is found at index: ");

    for (int i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            System.out.println(i);
            return i;
        }
    }

    throw new NoSuchElementException(„Element not found in array“);
 }
相关问题