更新時(shí)間:2022-12-21 12:20:14 來源:動(dòng)力節(jié)點(diǎn) 瀏覽6034次
Java數(shù)組求最大值的方法有哪些?動(dòng)力節(jié)點(diǎn)小編來告訴大家。
方法一:直接法,求最小值類似
public class Deno05ArrayMax {
public static void main(String[] args) {
//數(shù)據(jù)類型可指定
int [] array = {5,15,20,30,10000};
int max = array[0];//假設(shè)第一個(gè)值為最大值
for (int i = 1; i < array.length; i++) { //和后面的數(shù)進(jìn)行比較
if(array[i] > max) {
max = array[i];
}
}
System.out.println("最大值是:" + max);
}
}
方法二:調(diào)用方法求最大值,求最小值類似
public class Demo02Method {
public static void main(String[] args) {
int [] array = {5,15,35};
int max = getMax(array);
System.out.println("最大值:" + max);
}
//有返回值,含參
public static int getMax (int [] array) {
int max = array[0]; //局部變量寫在方法內(nèi)部
for (int i = 1; i < array.length; i++) {
if (array[i] > max ) {
max = array[i];
}
}
return max;
}
}
方法三:三元運(yùn)算符,求最小值類似
public class Demo02Method {
public static void main(String[] args) {
int[] arr = {5, 2, 3, 12,10,11,17,1,-1,-8};
int result = arr[0];
for (int i = 1; i < arr.length; i++){
// ? 前面的表達(dá)式為條件判斷
//邏輯為:如果條件表達(dá)式成立則執(zhí)行result,否則執(zhí)行arr[i]
result = (arr[i] < result ? result : arr[i]);
}
System.out.println("最大值為:" + result);
}
}
方法四:面向?qū)ο笳{(diào)用,求最小值類似
public class Demo02Method {
int [] arr = {9,20,5,6,1,3,7,2,4};
int num = arr[0];
public static void main(String args[]) {
Demo02Method max=new Demo02Method();
//調(diào)用方法
max.getMax();
}
public void getMax() {
for (int i = 0; i < arr.length; i++) {
if(arr[i] > arr[0]) {
num = arr[i];
}
}
System.out.println("最大值為:" + num);
}
}
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743