三種Java求最大值的方法
普通方法:
public class Max {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5,10,11,15,100,-1,-4.5}; //定義一維數(shù)組
double num = myList[0]; //0為第一個數(shù)組下標
for (int i = 0; i < myList.length; i++) { //開始循環(huán)一維數(shù)組
if (myList[i] > num) { //循環(huán)判斷數(shù)組元素
num = myList[i]; } //賦值給num,然后再次循環(huán)
}
System.out.println("最大值為" + num); //跳出循環(huán),輸出結(jié)果
}
}
三元運算符:
public class Max {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5,10,11,15,1,-1,-4.2}; //定義一維數(shù)組
double num = myList[0]; //0為第一個數(shù)組下標
for (int i = 0; i < myList.length; i++){ //開始循環(huán)一維數(shù)組
num=(myList[i] < num?num: myList[i]); //三元運算符,詳情看注解
}
System.out.println("最大值為" + num); //跳出循環(huán),輸出結(jié)果
}
}
注解:三元運算符的語法是 條件 ? 結(jié)果1 : 結(jié)果2;優(yōu)點代碼簡潔,缺點可讀性差
例子:int a,b,c;
a=2;b=3;
c=a>b?100:200;
語意:如果a>b,c=100;a<b,c=200
一般函數(shù)/方法:
public class Max {
double[] myList = {1.9, 2.9, 3.4, 100,3.5,10,11,12,13,-1};
double num = myList[0];
void getValue(){ //創(chuàng)建一般方法
for (int i = 0; i < myList.length; i++) {
num=(myList[i] < num?num: myList[i]);//三元運算符
}
System.out.println("最大值為" + num);
}
public static void main(String args[]){
Max max=new Max(); //創(chuàng)建對象
max.getValue(); //通過對象調(diào)用一般方法
}
}
注解:方法三需要用到面向?qū)ο蟮乃枷?/p>
相關(guān)文章
基于SpringBoot中activeMq的JmsTemplate的實例
這篇文章主要介紹了基于SpringBoot中activeMq的JmsTemplate的實例問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
詳解Lombok安裝及Spring Boot集成Lombok
這篇文章主要介紹了詳解Lombok安裝及Spring Boot集成Lombok,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03
Eclipse 開發(fā)java 出現(xiàn)Failed to create the Java Virtual Machine錯誤
這篇文章主要介紹了Eclipse 開發(fā)java 出現(xiàn)Failed to create the Java Virtual Machine錯誤解決辦法的相關(guān)資料,需要的朋友可以參考下2017-04-04
Redis原子計數(shù)器incr,防止并發(fā)請求操作
這篇文章主要介紹了Redis原子計數(shù)器incr,防止并發(fā)請求操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
Mybatis實現(xiàn)關(guān)聯(lián)關(guān)系映射的方法示例
本文主要介紹了Mybatis實現(xiàn)關(guān)聯(lián)關(guān)系映射的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
BeanUtils.copyProperties()屬性名相同但是類型不同問題
這篇文章主要介紹了BeanUtils.copyProperties()屬性名相同但是類型不同問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-09-09

