go to previous page   go to home page   go to next page hear noise highlighting
if ( booleanExpression ){
     one or more statements
}else{
     one or more statements }

Answer:

Yes. Logically it is the same as:

if ( booleanExpression )
{
    one or more statements
}
else 
{
    one or more statements 
}

Some programmers use the first style to "save" lines. This was once desirable when computer monitors could display only 20 lines at a time. Programmers used a line-saving style so they could see more of their program on the screen. But that style makes it easier to overlook some types of errors, which leads to more debugging time. (This has been shown in experimental studies.) Now that monitors display many more lines, it is wise to use a style that leads to fewer errors.

You still see line-saving styles in books because they use less paper and decrease printing costs. But when a program is displayed on a monitor, lines are free, and the style you use should emphasize clarity.


Asking the Right Question

Say that you are shopping at the Mall and find a $44.95 sweater you like, but, due to an impulsive cookie purchase, you might not have enough money. Below is a program that decides if you get the sweater.

The reserved word final in the fifth line says that the value held in price will not change during the run of the program. When you use final, the compiler reject any statement that tries to change the value. This is useful for preventing bugs.

Why pennies? Programs that deal with financial matters frequently do their calculations using integers. As you have seen, floating point is not exact. It would probably work OK for this program, though.


import java.util.Scanner;
public class SweaterPurchase
{
  public static void main (String[] args)
  { 
    final int price = 4495;    // price in cents

    Scanner scan = new Scanner( System.in );
 
    int cash;                       

    System.out.println("How much do you have, in pennies?");
    cash   = scan.nextInt();     
    
    if (   )
      System.out.println("You can buy the sweater." );
    else
    {
      System.out.println("You can't buy the sweater." );
      System.out.println("You need " + (price-cash) + " more cents." );
    }

  }
}

QUESTION 7:

What boolean expression should go into the blank? (Assume that there is no sales tax.)


go to previous page   go to home page   go to next page