Several Choices

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

The "opposite" of   <=   is   > .

Several Choices

racingstripes

Often there are several options that might be included in a major purchase. Each one might be accepted or rejected. Pretend you are buying a new car:

You have decided to buy a new sports car. The base price is $20,000. There are two options:

  • pin strips — $250
  • anti-lock brakes — $800

The price of the car is the base price plus the price of the options. Write a program that calculates the price of the car.

Here is an incomplete version. The user is expected to enter "1" to mean true and "0" to mean false. (There are better ways to do this which will be covered later in these notes.)

import java.util.Scanner;
class CarPurchase
{
  public static void main (String[] args) 
  { 
    final int basePrice  = 2000000;   // base price in cents
    final int pinPrice   =   25000;   // pin stripe price
    final int brakePrice =   80000;   // anti-lock brake price

    Scanner scan = new Scanner( System.in );
 
    int answer;
    int totalCost = basePrice;

    System.out.print("Do you want pin stripes (0 or 1)? ");
     
    answer = scan.nextInt();        
    if (  )
    {
      totalCost = totalCost + pinPrice;
    }

    System.out.print("Do you want anti-lock brakes (0 or 1)? ");
    answer = scan.nextInt(); 
    if (  )
    {
      totalCost = totalCost + brakePrice;
    }

    System.out.println("Total cost is: $" + 
        (totalCost/100) + "." + totalCost%100 );
 
  }
}

Notice how the number in totalCost is accumulated: it is initialized in its declaration, then added to in each of the true branches.

QUESTION 10:

Fill in the two blanks to complete the program. You may wish to copy the program to an editor and try it out.