首页 文章

用户在数组中输入10个数字如何编写代码来查找该数字并输出它在数组中的位置?

提问于
浏览
0

Java中的数组很新,但我给出的问题是:

“在您的main方法中,提示用户输入十个数字并将它们存储在一个数组中 . 编写一个名为find的方法,返回数组中特定数字第一次出现的位置 . 如果该数字不在列表中,你的方法应该返回-1 . 从main,提示用户输入一个数字,调用find方法,并从main显示结果给用户 . 如果方法返回-1,告诉用户该数字不在不要在find方法中与用户交互 . 方法的签名必须是:public static int find(int [] arr,int thingToFind)“

输出示例:

Enter ten numbers: 18 14 82 17 2 14 6 2 18 4
 What number would you like me to find? 2
 2 first occurs in the 5th place in the list.

 Enter ten numbers: 4 19 0 41 ­2 ­7 7 14 41 100
 What number would you like me to find? 99
 99 is not in the list.

我知道我需要一个循环来进入find方法,但不确定哪一个,我正在考虑for循环但不知道如何实现它 . 这是我现在的代码,是的,我知道我错过了很多,而这只是它的开始 . 不知道从哪里开始 .

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter 10 numbers ");
    int n = in.nextInt();
    int arr[] = new int[n];
  }

   public static int find(int[] arr, int thingToFind){

     }

   }

5 回答

  • 1

    我认为你的方法应该是这样的

    public static int find(int[] arr, int thingToFind){
    
    
            for(int i = 0;i<arr.length;i++){
                if(arr[i]==thingToFind){
                    return i+1;
                }
            }
            return -1;
    
        }
    
  • 1

    这将返回thingToFind的索引,如果未找到thingToFind,则返回-1 .

    public static int find(int[] arr, int thingToFind){
      int i;
      for(i = 0; i < arr.length(); i++){
        if(arr[i] == thingToFind){
          return i;
        }
      }
      return -1;
    }
    
  • 2
    void find(int[]arr, int tofind){
       for (int i: arr){
            if (arr[i]==toFind){
               System.out.println(tofind+" first occurs at "+i+"th place in the array")
            return
       System.out.println("not found")
    

    }}

  • 2

    你还有一段路要走 . 你知道你有10个数字,所以你可以写

    int arr[] = new int[10];
    

    在你读任何数字之前 . 此外,您需要一个循环来读取您的数字 . 你可以写

    arr[0] = in.nextInt();
    arr[1] = in.nextInt();
    arr[2] = in.nextInt();
    

    等等,但你可以做得更好,对吧?

  • 2

    您将需要一个for循环,因为您可以使用索引(通常为 int i = 0 )来访问要迭代的数组元素 . 在每个循环中,检查i处的元素是否是您要查找的数字 . 如果是,请返回i . 循环之后,返回-1,因为如果找不到数字,则只能到达此部分 .

    你可能需要的一些东西:

    • arr.length 是数组的大小

    • arr[i] 是位置i的元素

相关问题