共計(jì) 704 個字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
在 Java 中實(shí)現(xiàn)查找功能可以利用循環(huán)和條件判斷來遍歷數(shù)據(jù)并進(jìn)行比較。下面是一個示例代碼,演示如何在一個整數(shù)數(shù)組中查找指定的數(shù)字并返回其索引位置:
public class SearchExample {public static int search(int[] arr, int target) {for (int i = 0; i < arr.length; i++) {if (arr[i] == target) {return i; // 找到目標(biāo)數(shù)字,返回索引位置}
}
return -1; // 數(shù)組中不存在目標(biāo)數(shù)字,返回 -1
}
public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5};
int target = 3;
int index = search(arr, target);
if (index != -1) {System.out.println(" 目標(biāo)數(shù)字 " + target + " 的索引位置為: " + index);
} else {System.out.println(" 目標(biāo)數(shù)字 " + target + " 不存在數(shù)組中 ");
}
}
}
在這個例子中,我們定義了一個 search
方法,它接受一個整數(shù)數(shù)組和一個目標(biāo)數(shù)字作為參數(shù)。在 search
方法中,我們使用一個 for
循環(huán)遍歷整個數(shù)組,并使用 if
條件判斷來檢查當(dāng)前元素是否等于目標(biāo)數(shù)字。如果找到目標(biāo)數(shù)字,我們返回它的索引位置;如果數(shù)組中不存在目標(biāo)數(shù)字,我們返回 -1。
在 main
方法中,我們創(chuàng)建一個整數(shù)數(shù)組 arr
并指定目標(biāo)數(shù)字為 3。然后,我們調(diào)用 search
方法來查找目標(biāo)數(shù)字在數(shù)組中的索引位置,并將結(jié)果打印輸出。如果目標(biāo)數(shù)字不存在數(shù)組中,我們也會相應(yīng)地進(jìn)行輸出。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完