if / else statements

This example gives a 20% tip if the value of service is 'Y' or 'y'. When the user enters an answer as a character, 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
17
18
19
//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();
		if(service=="Y" || service=="y")
		    tip=cost*0.20; //20% for good service
		else 
		    tip=cost*0.15; //15% if not
		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.

flowchart

NEXT: