Three methods for finding the maximum value in Java and three methods for obtaining the maximum value in java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.