普通方法:
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}; //定義一維數組double num = myList[0]; //0為第一個數組下標for (int i = 0; i < myList.length; i++) { //開始循環一維數組if (myList[i] > num) { //循環判斷數組元素num = myList[i]; } //賦值給num,然後再次循環} System.out.println("最大值為" + num); //跳出循環,輸出結果} }三元運算符:
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}; //定義一維數組double num = myList[0]; //0為第一個數組下標for (int i = 0; i < myList.length; i++){ //開始循環一維數組num=(myList[i] < num?num: myList[i]); //三元運算符,詳情看註解} System.out.println("最大值為" + num); //跳出循環,輸出結果} }註解:三元運算符的語法是條件? 結果1 : 結果2;優點代碼簡潔,缺點可讀性差
例子:int a,b,c;
a=2;b=3;
c=a>b?100:200;
語意:如果a>b,c=100;a<b,c=200
一般函數/方法:
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(){ //創建一般方法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(); //創建對象max.getValue(); //通過對象調用一般方法}}註解:方法三需要用到面向對象的思想