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

标签 java

对 Java 中的数组非常陌生,但我要解决的问题是:

"In your main method, prompt the user to enter ten numbers and store them in an array. Write a method called find that returns the position of the first occurrence of a particular number in the array. If the number is not in the list, your method should return ‐1. From main, prompt the user to enter a number, call the find method, and display the result to the user from main. If the method returned ‐1, inform the user that the number was not in the list. Do not interact with the user from within the findmethod. The signature of your method must be: 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){

     }

   }

最佳答案

这将返回 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;
}

关于java - 用户在数组中输入 10 个数字,我该如何编写代码来查找该数字并输出它在数组中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677549/

相关文章:

java - Dagger 的 2 个 Activity 的单个实例

java - Jackson Xml 重复标签名称

java - 我可以处理的 Spring 回调

java - 在 Spring Boot 上使用正确的方言 PostgreSQL

java - 帮助构建正则表达式

java - 向 String 添加转义符,可能吗?

java - Apache poi 从文本框中获取表格

java - 如何在不知道类名的情况下运行Java类

java - this关键字的概念和同步

java - 无法使用 Java 在命令提示符下通过 PATH 运行命令?