If-else statement judges:
import java.util.Scanner;public class AbsoluteValue { public static void main(String[] args){ Scanner input=new Scanner(System.in);//Declare the scanner variable System.out.println("Please enter the value");//The system prompts to enter try{ //Speak the exception while(true){ //Continue to read the value entered by the user float num=input.nextFloat();//Capt to a floating point number if(num==0){ //If the user enters -0, output 0 System.out.println("Absolute value is"+0); } else if(num>0){ System.out.println("absolute value is"+num); } else if(num<0){ System.out.println("absolute value is"+(-num)); } } } catch(Exception e){ //Exception handling System.out.println("Please enter correctly"); e.printStackTrace(); //Print the location and reason of the error in the program} } } }Triple operator judgment:
import java.util.Scanner;public class AbsoluteValue { public static void main(String[] args){ Scanner input=new Scanner(System.in);//Declare the scanner variable System.out.println("Please enter the value");//The system prompts to enter try{ //Speak the exception while(true){ //Continue to read the value entered by the user float num=input.nextFloat();//Captively convert to a floating point number if(num==0){ //If the user enters -0, output 0 System.out.println("Absolute value is"+0); } else{ num=(num>0?num:-num);//The ternary operator System.out.println("Absolute value is"+num); } } } catch(Exception e){ //Exception handling System.out.println("Please enter correctly"); e.printStackTrace(); //Print the location and reason for the error in the program} } } }Note: Is the syntax of the ternary operator condition? Result 1: Result 2; Advantages are concise in code, but disadvantages are poor readability
Example: int a,b,c;
a=2;b=3;
c=a>b?100:200;
Semantics: If a>b,c=100;a<b,c=200