Day 07 數(shù)組

數(shù)組

查找下標(biāo):

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("傳入?yún)?shù)不合法");

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. 參數(shù)合法性判斷

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

System.out.println("傳入?yún)?shù)不合法!");

return -1;

}

//2. 假設(shè)下標(biāo)為0的元素是數(shù)組中的最大值

int index = 0;

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

//如果當(dāng)前index下標(biāo)的數(shù)據(jù)小于下標(biāo)為i的元素,證明當(dāng)前

//Index保存的不是最大值,把i的值賦值給index 保存

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

index = i;

}

}

return index;

}

public static void getNumberFromStdin(int[] array) {

//1. 參數(shù)合法性判斷

if (null == array) {

System.out.println("傳入?yún)?shù)不合法");

return;

}

Scanner sc = new Scanner(System.in);

//2. 利用for循環(huán)從鍵盤上獲取用戶輸入的int類型數(shù)據(jù)

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

array[i] = sc.nextInt();

}

}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容