java项目汽配管理系统需求: 设计一个方法, 查找元素在数组中的索引位置 已知一个数组 arr = {19, 28, 37, 46, 50}; 键盘录入一个数据,查找该数据在数组中的索引。 并在控制台输出找到的索引值。 如果没有查找到,则输出-1
时间: 2025-01-18 07:05:39 浏览: 29
以下是一个Java方法,用于查找元素在数组中的索引位置,并根据要求输出结果:
```java
import java.util.Scanner;
public class AutoPartsManagementSystem {
// 方法:查找元素在数组中的索引位置
public static int findIndex(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1; // 如果没有找到,返回-1
}
public static void main(String[] args) {
int[] arr = {19, 28, 37, 46, 50};
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要查找的数字:");
int target = scanner.nextInt();
int index = findIndex(arr, target);
if (index != -1) {
System.out.println("元素 " + target + " 在数组中的索引位置是:" + index);
} else {
System.out.println("没有查找到元素 " + target + ",输出-1");
}
scanner.close();
}
}
```
这个程序包含以下主要部分:
1. `findIndex` 方法:接收一个数组和目标值作为参数,遍历数组查找目标值。如果找到,返回其索引;否则返回 -1。
2. `main` 方法:
- 定义了给定的数组 `arr`。
- 使用 `Scanner` 类从键盘读取用户输入。
- 调用 `findIndex` 方法查找输入值的索引。
- 根据返回的索引值,输出相应的结果。
3. 程序执行流程:
- 程序首先提示用户输入要查找的数字。
- 然后调用 `findIndex` 方法查找该数字在数组中的索引。
- 最后,根据查找结果在控制台输出相应的信息。
这个程序满足了用户的需求,可以查找元素在数组中的索引位置,并在控制台输出找到的索引值或 -1(如果未找到)。
阅读全文
相关推荐


















