Three methods for finding the maximum value in Java and three methods for obtaining the maximum value in java
Common method:
Public class Max {public static void main (String [] args) {double [] myList = {1.9, 2.9, 3.4, 3.5, 15,100, 4.5,-1 }; // define the one-dimensional array double num = myList [0]; // 0 is the first array subscript for (int I = 0; I <myList. length; I ++) {// starts to loop through the one-dimensional array if (myList [I]> num) {// cyclically judges the array element num = myList [I];} // assign a value to num and then loop again} System. out. println ("maximum value:" + num); // jump out of the loop, output result }}
Ternary operators:
Public class Max {public static void main (String [] args) {double [] myList = {1.9, 2.9, 3.4, 3.5, 4.2,-1 }; // define the one-dimensional array double num = myList [0]; // 0 is the first array subscript for (int I = 0; I <myList. length; I ++) {// start to cycle the one-dimensional array num = (myList [I] <num? Num: myList [I]); // triplicate operator. For details, see the annotation} System. out. println ("maximum value" + num); // jump out of the loop, output result }}
Note: Is the syntax of the ternary operator A condition? Result 1: result 2: The advantage code is concise and the disadvantage is less readable.
Example: int a, B, c;
A = 2; B = 3;
C = a> B? 100:200;
Meaning: If a> B, c = 100; a <B, c = 200
General functions/methods:
Public class Max {double [] myList = {1.9, 2.9, 3.4, 100, 3.5,-1}; double num = myList [0]; void getValue () {// create a general method for (int I = 0; I <myList. length; I ++) {num = (myList [I] <num? Num: myList [I]); // ternary operator} System. out. println ("maximum value" + num);} public static void main (String args []) {Max max = new Max (); // create object max. getValue (); // call a general method through an object }}
Note: method 3 requires the use of Object-oriented Thinking