Conditional operator: ?

This example gives a 20% tip if the value of service is "Y" or "y". When the user enters an answer as a String, it is important to test for both upper case and lower case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Tip based on service
package mealcost;
import java.util.*;
public class CalcualteTip {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); //do just once
    double cost,tip;
    String service;
    System.out.print("Enter the cost of the meal: $");
    cost=keyboard.nextDouble();
    System.out.print("Was the service good (Y or N):");
    service=keyboard.next();
    tip=(service=="Y" || service=="y")? cost*0.20: cost*0.15;
    System.out.println(String.format("The tip should be $%.2f",tip));
  }//main
}//class
CODE
Enter the cost of the meal: $12
Was the service good (Y or N):y
The tip should be $1.80

Enter the cost of the meal: $100
Was the service good (Y or N):n
The tip should be $15.00

Notice that we format the tip to 2 decimal places using String.format. The %$%.2f if replaced by the value of tip formatted to show exactly 2 decimal places.

Compare this to the program using if/else.

NEXT: For Loops