Day 07 数组

数组

查找下标:

class Demo1 {

public static void main(String[] args) {

int [] arr = {1, 3, 23, 34, 5, 56, 7, 8, 9, 10};

int ret = findIndex(arr, 34);

if (ret != -1) {

System.out.println("ret = " + ret );

}else {

System.out.println("not,found.!" );

}

}

public static int findIndex(int[] array,int number) {

if (null == array || array.length == 0) {

System.out.println("传入参数不合法");

return -1;

}

int index = -1;

for (int i = 0; i < array.length; i++) {

if (number == array[i]) {

index = i;

}

}

return index;  

}

}

查最大值:

public class Demo2 {

public static void main(String[] args) {

int[] arr = new int[10];

getNumberFromStdin(arr);

int ret = findMaxIndex(arr);

if (ret != -1) {

System.out.println("Max is " + arr[ret] + " at " + ret);

}

}

public static int findMaxIndex(int[] array) {

//1. 参数合法性判断

if (null == array || array.length == 0) {

System.out.println("传入参数不合法!");

return -1;

}

//2. 假设下标为0的元素是数组中的最大值

int index = 0;

for (int i = 1; i < array.length; i++) {

//如果当前index下标的数据小于下标为i的元素,证明当前

//Index保存的不是最大值,把i的值赋值给index 保存

if (array[index] < array[i]) {

index = i;

}

}

return index;

}

public static void getNumberFromStdin(int[] array) {

//1. 参数合法性判断

if (null == array) {

System.out.println("传入参数不合法");

return;

}

Scanner sc = new Scanner(System.in);

//2. 利用for循环从键盘上获取用户输入的int类型数据

for (int i = 0; i < array.length; i++) {

array[i] = sc.nextInt();

}

}

}

你可能感兴趣的:(Day 07 数组)