How to Combine Conditions in Java Statements - dummies

# How to Combine Conditions in Java Statements

Java allows you to do almost anything you want, if you know what you’re doing. Here’s a handy example of the use of logical operators. A movie theater posts its prices for admission.

Regular price: \$9.25

Kids under 12: \$5.25

Seniors (65 and older): \$5.25

Because the kids and seniors’ prices are the same, you can combine these prices into one category. (That’s not always the best programming strategy, but do it anyway for this example.) To find a particular moviegoer’s ticket price, you need one or more if statements. You can structure the conditions in many ways.

```import java.util.Scanner;
class TicketPrice {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int age;
double price = 0.00;
System.out.print("How old are you? ");
age = keyboard.nextInt();
if (age >= 12 && age < 65) {
price = 9.25;
}
if (age < 12 || age >= 65) {
price = 5.25;
}
System.out.print(price);
System.out.print(". ");
System.out.println("Enjoy the show!");
keyboard.close();
}
}```

When you turn 12, you start paying full price. You keep paying the full price until you become 65. At that point, you pay the reduced price again.

The pivotal part of code is the lump of if statements in the middle.

What are the meaning of these conditions?

• The first if statement’s condition tests for the regular price group. Anyone who’s at least 12 years of age and is under 65 belongs in this group.

• The second if statement’s condition tests for the fringe ages. A person who’s under 12 or is 65 or older belongs in this category.

When you form the opposite of an existing condition, you can often follow the pattern. The opposite of >= is <. The opposite of < is >=. The opposite of && is ||.

If you change the dollar amounts in Listing 10-1, you can get into trouble. For example, with the statement price = 5.00, the program displays Please pay \$5.0. Enjoy the show! This happens because Java doesn’t store the two zeros to the right of the decimal point (and Java doesn’t know or care that 5.00 is a dollar amount).