go to previous page   go to home page   go to next page hear noise highlighting

Answer:

    if (  cash >= price )

You (hopefully) picked a relational operator that yields true when the user CAN pay for the sweater.


Reverse Logic

Here is a run of the program:

How much do you have, in pennies?
5000
You can buy the sweater.

The true block is executed because the boolean expression is true. 5000 is greater or equal to 4495. Here is another run of the program:

How much do you have, in pennies?
2000
You can't buy the sweater.
You need 2495 more cents.

The false block is executed because the boolean expression is false.

Boolean expressions are always true or false. Use the correct relational operator (==, >, <, >=, <=, != ) to ask a question that is true when you want the true branch to be executed. If the statements inside of the two branches are reversed, pick a different relational operator so the program does the same thing as before.

Here is the program with the statements in the true and false branches reversed.


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't buy the sweater." );
      System.out.println("You need " + (price-cash) + " more cents." );
    }
    else
      System.out.println("You can buy the sweater." );

  }
}

QUESTION 8:

What boolean expression should fill the blank?


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