Java method to determine the absolute value, java to determine the absolute value
If-else statement judgment:
Import java. util. extends; public class AbsoluteValue {public static void main (String [] args) {extends input = new evaluate (System. in); // declare the scanner variable System. out. println ("enter a value"); // The system prompts you to enter try {// listen for exceptions while (true) {// continuously read the value float num = input. nextFloat (); // force convert to floating point if (num = 0) {// if the user inputs-0, the output is 0 System. out. println ("absolute value" + 0);} else if (num> 0) {System. out. println ("absolute value" + num);} else if (num <0) {System. out. println ("absolute value" + (-num) ;}} catch (Exception e) {// Exception handling System. out. println ("Enter it correctly"); e. printStackTrace (); // print the location and cause of the error in the program }}}
Trielement operator judgment:
Import java. util. extends; public class AbsoluteValue {public static void main (String [] args) {extends input = new evaluate (System. in); // declare the scanner variable System. out. println ("enter a value"); // The system prompts you to enter try {// listen for exceptions while (true) {// continuously read the value float num = input. nextFloat (); // force convert to floating point if (num = 0) {// if the user inputs-0, the output is 0 System. out. println ("absolute value" + 0);} else {num = (num> 0? Num:-num); // ternary operator System. out. println ("absolute value" + num) ;}} catch (Exception e) {// Exception handling System. out. println ("Enter it correctly"); e. printStackTrace (); // print the location and cause of the error in the program }}}
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