package com.lcn.day05;
public class ArrayDemo8 {
/**
* 输出数组指定元素的下标
*/
public static void main(String[] args) {
//定义一个数组
int[] array = new int[]{123,456,789,321,654,987};
int index = printArray(array,321);
System.out.println("321对应的下标是:"+index);
//查询没有的数据
int index1 = printArray(array,10000);
System.out.println("10000对应的下标是:"+index1);
}
//遍历数组
public static int printArray(int[] array,int value){
for(int i = 0;i<array.length;i++){
if(array[i]==value){
return i;
}
}
return -1;//当if条件不成立时,默认返回一个负数值-1
}
}
输出:
321对应的下标是:3
10000对应的下标是:-1

本文介绍了一个简单的Java程序,该程序能够遍历整型数组并返回指定元素的下标位置。如果元素不存在于数组中,则返回-1。通过两个示例展示了如何使用此程序来查找数组中的特定值。

3382

被折叠的 条评论
为什么被折叠?



