If the answer is true something extra is done. If the answer if false nothing is done. (If you are not hungry you don't buy cookies.)
if
The "cookie problem" is about whether you should add a visit to the cookie shop. This program helps make this important decision. Rate three factors on a scale of 1 to 10. If the combination of hunger, aroma, and visual appeal exceeds a threshold of 15, buy cookies!.
import java.util.Scanner ; public class CookieDecision { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); int hunger, look, smell ; System.out.print("How hungry are you? (1-10): "); hunger = scan.nextInt(); System.out.print("How nice do the cookies look? (1-10): "); look = scan.nextInt(); System.out.print("How nice do the cookies smell? (1-10): "); smell = scan.nextInt(); if ( (hunger + look + smell ) > 15 ) System.out.println("Buy cookies!" ); System.out.println("Continue down the Mall."); } }
Unlike the decisions of the previous chapter, there is only a single branch (corresponding to true).
if
statement asks a question comparing two numbers.The statement
System.out.println("Continue down the Mall.")
will always be executed.
You rate hunger, appearance, and aroma as 4, 6, and 9, respectively. Do you buy cookies?