switch: looking at one variable

In this example, we calculate the tip as 20% if the service is 'Y' or 'y'. Otherwise, the tip is 15%Compare this to the example using if/else.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Tip based on service
package mealcost;
import java.util.*;
public class CalculateTip {
  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();
    switch(service) {
      case "Y": case "y": tip=cost*0.20; break;//20% for good service
      case "N": case "n": tip=cost*0.15; break;//15% for ok service
      default: System.out.println("not a valid answer"); tip=0.00; 
    }
    System.out.println(String.format("The tip should be $%.2f",tip));
  }//main
}//class
CODE

Some sample output:

Enter the cost of the meal: $20
Was the service good (Y or N):y
The tip should be $4.00

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

Enter the cost of the meal: $25
Was the service good (Y or N):s
not a valid answer
The tip should be $0.00

NEXT: