Chapter 5

<< Chapter 4 | HomeworkTrailIndex | Chapter 6 >>

Binary Game

Decisions


Now that we have the ability to use conditional statements (the if statement), we can enhance many of our previous projects.

Demo Code

public String getOpinion(String color)
{
        if (color.equals("red") )
        {
            return "That's nice";
        }
        if (color.equals("green") )
        {   
            return "Oh I like that alot";
        }
        return "That's terrible";
}

P5.1 Update the Quadratic Equation Class to detect when there are no real solutions Recall from your algebra class that when the discriminant is less than zero ({⚠ $\sqrt{b^2-4ac} <0$}), the roots are complex and there are no solutions that are real numbers. We can either find the complex roots or simply report that there are no real solutions. We can add the method hasRealSolutions() to return a true or false (type boolean) value.

Do the 1,2,...,10 Game Lab

Do the Joust Game Lab

Try the Javabat Logic puzzles

Use a truth table to show not(p and q) is equivalent to (not p) or (not q) (deMoivre Theorem)

pq!p!qp && q!(p && q)!p || !q
TT     
TF     
FT     
FF     

Use a truth table to show not(p or q) is equivalent to (not p) and (not q) (deMoivre Theorem)

pq!p!qp || q!(p || q)!p && !q
TT     
TF     
FT     
FF     

Hi-Low Game

Review Exercises

  • R5.1 Find Errors in if Statements
a. if quarters > 0 then System.out.println(quarters + " quarters");
b. if (1 + x > Math.pow(x, Math.sqrt(2)) y = y + x;
c. if (x = 1) y ++; else if (x = 2) y = y + 2;
d. if (x && y == 0) { x = 1; y = 1; }
e. if (1 <= x <= 10) System.out.println(x);
f. if (! s.equals("nickels") || ! s.equals("pennies")|| !s.equals("dimes") || !s.equals("quarters"))System.out.print("Input error!");
g. if (input.equalsIgnoreCase("N") || "NO")return;
h. int x = Integer.parseInt(input) ;if (x ! = null) y = y + x;
i. language = "English";
if (country.equals("US"))
if (state.equals("PR")) language = "Spanish";
else if (country.equals("China"))
language = "Chinese";
  • R5.6 Use a truth table to find all the possible ways !(p &&(q ||!r) is true
pqr(p && q)!r(p && q) || !rq || !rp && (q || !r)!(p && (q || !r))
FFF      
FFT      
FTF      
FTT      
TFF      
TFT      
TTF      
TTT      
  • R5.9 Explain the difference between
s = 0;
if (x > 0) s ++;
if (y >	0) s ++;

and

 
s = 0;
if (x > 0) s ++;
else if (y > 0) s ++;
  • R5.10 Use de Morgan's law to simplify the following Boolean expressions.
(a) ! (x > 0 && y > 0)
(b) !(x ! = 0 || y ! = 0)
(c) !(country.equals("US") && ! state.equals("HI") && !state.equals("AK"))
(d) ! (x % 4 ! = 0 | | ! (x % 100 == 0 && x % 400 == 0))
  • R5.13 Explain the difference between the tests

r == s and r.equals(s) where both r and s are of type Rectangle.

  • R5.17 Explain why it is more difficult to compare floating-point numbers than integers. Write Java code to test whether an integer n equals 10 and whether a floating-point number x equals 10.

Programming Exercises

Do two of these for for 8 Points, three for 9 points, four for 10 points and all five of these for 11 points.

  • P5.2 Playing card translation. See page 221 for full details (for example 4S should be Four of Spades, and if the format is in correct the getDescription method should return "Unknown"

Here is a test Class for you:

import java.util.Scanner;

/**
   This is a test for the Card class, which outputs the full
   description of a deck of cards.
*/
public class CardPrinter
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Enter the card notation:");
      String input = in.nextLine();
      Card card = new Card(input);
      System.out.println(card.getDescription());
   }
}
  • P5.3 Sort 3 Numbers

Use the following class as your main class:

import java. util.Scanner;

/**
   This is a test class for DataSet.
*/
public class DataSorter
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Please enter three numbers:");
      double num1 = in.nextDouble();
      double num2 = in.nextDouble();
      double num3 = in.nextDouble();

      DataSet s = new DataSet(num1, num2, num3);

      System.out.println("The inputs in sorted order are:\n"
         + s.getSmallest() + "\n"
         + s.getMiddle() + "\n"
         + s.getLargest());
   }
}

Complete the following class in your solution:

/**
   This class finds the smallest, middle, and largest of
   three numbers.
*/
public class DataSet
{
   /**
      Constructs a data set that processes three numbers.
      @param num1 the first number to sort
      @param num2 the second number to sort
      @param num3 the third number to sort
   */
   public DataSet(double num1, double num2, double num3)
   {
      . . .
   }

   /**
      Gets the smallest number in the data set.
      @return smallest the smallest of three numbers
   */
   public double getSmallest()
   {
      . . .
   }

   /**
      Gets the largest number in the data set.
      @return largest the largest of three numbers
   */
   public double getLargest()
   {
      . . .
   }

   /**
      Gets the middle number in the data set.
      @retu rn mi ddl e the middle number of three numbers
   */
   public double getMiddle()
   {
      . . .
   }
   . . .
}
  • P5.5 Write a program that translates a letter grade into a number grade. Letter grades are A B C D F, possibly followed by + or -. Their numeric values are 4, 3, 2, 1, and 0. There is no F+ or F-. A + increases the numeric value by 0.3, a -decreases it by 0.3. However, an A+ has the value 4.0.
Enter a letter grade:
B-
Numeric value: 2.7.

Use a class Grade with a method getNumericGrade. Use the following class as your main class:

import java. util.Scanner;

/**
   This class prints the numeric value of a letter grade given by the user.
*/
public class GradePrinter
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter a letter grade:");
      String input = in.nextLine();
      Grade g = new Grade(input);
      double grade = g.getNumericGrade();
      System.out.println("Numeric value: "+ grade);
   }
}
  • P5.7 Sort Three strings

Write a program that reads in three strings and prints the lexicographically smallest and largest one:

Please enter three strings:
Tom
Dick
Harry
The inputs in sorted order are:
Dick
Harry
Tom

Use the following class as your main class:

import java. util.Scanner;

/**
   This is program sorts three strings.
*/
public class StringSorter
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Please enter three strings:");
      String str1 = in.nextLine();
      String str2 = in.nextLine();
      String str3 = in.nextLine();

      StringSet s = new StringSet(str1, str2, str3);

      System.out.println("The inputs in sorted order are:\n"
         + s.getSmallest() + "\n"
         + s.getMiddle() + "\n"
         + s.getLargest());
   }
}

Complete the following class in your solution:

/**
   This class finds the smallest, middle, and largest of
   three strings.
*/
public class StringSet
{
   /**
      Constructs a string set that processes three strings.
      @param str1 the first string to sort
      @param str2 the second string to sort
      @param str3 the third string to sort
   */
   public StringSet(String str1, String str2, String str3)
   {
      . . .
   }

   /**
      Gets the smallest string in the string set.
      @return smallest the smallest of three strings
   */
   public String getSmallest()
   {
      . . .
   }

   /**
      Gets the largest string in the string set.
      @return largest the largest of three strings
   */
   public String getLargest()
   {
      . . .
   }

   /**
      Gets the middle string in the string set.
      @return middle the middle string of three strings
   */
   public String getMiddle()
   {
      . . .
   }
   . . .
}

It should be a void method that checks for four possible conditions:

  1. A win is when there are no targets left (Hint: targets.size() returns the number of targets )
  2. A loss due to lack of both ammo and powder
  3. A loss due to a lack of ammo only
  4. A loss due to lack of powder

When one of these conditions exist, the String field message should report:

  1. "You win with XXX cannonballs and YYY gunpowder left!"
  2. "Game Over-- out of cannonballs and gunpowder"
  3. "Game Over-- out of cannonballs"
  4. "Game Over-- out of gunpowder"