Learn Java · lesson 13 of 61 · about 9 minutes
Project: Free Popcorn
Read whether the customer is a member and decide who gets free popcorn: a rule built from equals, ||, && and ? :.
What you'll learn
- Translate rules into conditions
- Compare typed text with equals
- Report the result with a ternary
The popcorn rule
The cinema gives away popcorn. The rule:
1. Members get free popcorn, and so does any group of 6 or more
2. But only when the booking can go ahead
The customer types yes or no when asked if they're a member. In Java:
(isMember || tickets >= 6) && canBook
Picking a message
condition ? a : b picks one of two values: a when the condition is true, b when it's false. It's perfect for the final message: popcorn ? "Free popcorn!" : "No free popcorn".
The rule on its own
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String member = in.next();
int tickets = in.nextInt();
boolean canBook = true;
boolean isMember = member.equals("yes");
boolean popcorn = (isMember || tickets >= 6) && canBook;
System.out.println(popcorn ? "Free popcorn!" : "No free popcorn");
}
}Output
Free popcorn!Test the edges
Rules break at their edges. A group of 6 should get popcorn and a group of 5 shouldn't, a member gets it with any group size, and a booking that can't go ahead stops even a member. Check each one before you trust the rule.
Tip
The brackets matter: without them && is worked out first, so a member would get popcorn even when the booking can't go ahead. Java doesn't warn you about this, so the brackets are up to you.
Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.