Chapter 4: Rational ADT

//********************************************************************
//  Rational.java       Author: Lewis/Loftus/Cocking
//
//  Represents one rational number with a numerator and denominator.
//********************************************************************

public class Rational
{
   private int numerator, denominator;

   //-----------------------------------------------------------------
   //  Sets up the rational number by ensuring a nonzero denominator
   //  and making only the numerator signed.
   //-----------------------------------------------------------------
   public Rational (int numer, int denom)
   {
      if (denom == 0)
         denom = 1;

      // Make the numerator "store" the sign
      if (denom < 0)
      {
         numer = numer * -1;
         denom = denom * -1;
      }

      numerator = numer;
      denominator = denom;

      reduce();
   }

   //-----------------------------------------------------------------
   //  Returns the numerator of this rational number.
   //-----------------------------------------------------------------
   public int getNumerator ()
   {
      return numerator;
   }

   //-----------------------------------------------------------------
   //  Returns the denominator of this rational number.
   //-----------------------------------------------------------------
   public int getDenominator ()
   {
      return denominator;
   }

   //-----------------------------------------------------------------
   //  Returns the reciprocal of this rational number.
   //-----------------------------------------------------------------
   public Rational reciprocal ()
   {
      return new Rational (denominator, numerator);
   }

   //-----------------------------------------------------------------
   //  Adds this rational number to the one passed as a parameter.
   //  A common denominator is found by multiplying the individual
   //  denominators.
   //-----------------------------------------------------------------
   public Rational add (Rational op2)
   {
      int commonDenominator = denominator * op2.getDenominator();
      int numerator1 = numerator * op2.getDenominator();
      int numerator2 = op2.getNumerator() * denominator;
      int sum = numerator1 + numerator2;

      return new Rational (sum, commonDenominator);
   }

   //-----------------------------------------------------------------
   //  Subtracts the rational number passed as a parameter from this
   //  rational number.
   //-----------------------------------------------------------------
   public Rational subtract (Rational op2)
   {
      int commonDenominator = denominator * op2.getDenominator();
      int numerator1 = numerator * op2.getDenominator();
      int numerator2 = op2.getNumerator() * denominator;
      int difference = numerator1 - numerator2;

      return new Rational (difference, commonDenominator);
   }

   //-----------------------------------------------------------------
   //  Multiplies this rational number by the one passed as a
   //  parameter.
   //-----------------------------------------------------------------
   public Rational multiply (Rational op2)
   {
      int numer = numerator * op2.getNumerator();
      int denom = denominator * op2.getDenominator();

      return new Rational (numer, denom);
   }

   //-----------------------------------------------------------------
   //  Divides this rational number by the one passed as a parameter
   //  by multiplying by the reciprocal of the second rational.
   //-----------------------------------------------------------------
   public Rational divide (Rational op2)
   {
      return multiply (op2.reciprocal());
   }

   //-----------------------------------------------------------------
   //  Determines if this rational number is equal to the one passed
   //  as a parameter.  Assumes they are both reduced.
   //-----------------------------------------------------------------
   public boolean equals (Rational op2)
   {
      return ( numerator == op2.getNumerator() &&
               denominator == op2.getDenominator() );
   }

   //-----------------------------------------------------------------
   //  Returns this rational number as a string.
   //-----------------------------------------------------------------
   public String toString ()
   {
      String result;

      if (numerator == 0)
         result = "0";
      else
         if (denominator == 1)
            result = numerator + "";
         else
            result = numerator + "/" + denominator;

      return result;
   }

   //-----------------------------------------------------------------
   //  Reduces this rational number by dividing both the numerator
   //  and the denominator by their greatest common divisor.
   //-----------------------------------------------------------------
   private void reduce ()
   {
      if (numerator != 0)
      {
         int common = gcd (Math.abs(numerator), denominator);

         numerator = numerator / common;
         denominator = denominator / common;
      }
   }

   //-----------------------------------------------------------------
   //  Computes and returns the greatest common divisor of the two
   //  positive parameters. Uses Euclid's algorithm.
   //-----------------------------------------------------------------
   private int gcd (int num1, int num2)
   {
      while (num1 != num2)
         if (num1 > num2)
            num1 = num1 - num2;
         else
            num2 = num2 - num1;

      return num1;
   }
}

Chapter 3 – Slot Machine

September 24th, 2015

Classwork/Homework
Design and implement an application, YI_SloptMachine.java that simulates a simple slot machine in which three numbers between 0 and 9 are randomly selected and printed side by side. Print a statement saying all three of the numbers are the same, or any two of the numbers are the same, when this happens. Keep playing until the user chooses to stop.
Screen Shot 2014-09-16 at 2.47.15 PM

Homework:
Short answer 3.6 through 3.10.

Chapter 3 – Conditionals more features and assignment

Chapter 3: Program Statements More Notes

While Statement:

whileLoopFC

while ( condition )
{
   // statements block
}

A common mistake: an infinite loop. The loop will keep going forever.

whileStatmt

The do loop:

doFC

do
{
   // statements block
}
while ( condition );

The for loop:

forStatement

forFlowChart

for ( initialization; condition; update )
    {
      // block statements
    }

It is a sign of unbelievably bad taste to put unrelated conditions into the loop. ( lol )

The switch statement

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Class work:
Write a program HollePrinter_YI.java that switches the letters “e” and “o” in a string. Use the replace method repeatedly. Demonstrate that the string “Hello, World!” turns into “Holle, Werld!”

Chapter 3: Std Lib – Graphics Review

Classwork:

3.17 Design and implement an application that draws the side view of stair steps from the lower left to the upper right.

3.18 Design and implement an application that draws 100 circles of random color and random diameter in random locations. Make sure that in each case the whole circle appears in the visible area.

You can use the libraries from PU:
Screen Shot 2015-09-10 at 9.16.47 AM

 
Homework:
Short Answers 3.12 through 3.17
T/F 1 through 9

 
Chapter 3 Test Review
Review from the book the following material:
The “if” statement
Block Statement
Selection operator: ternary if
Brace layout
Indentation and tabs
Conditions with side effects
The “switch” statement
The “dangling” else
Boolean expressions
Multiple Relational operators
Confusing && and || conditions
Lazy evaluation of Boolean operators

Chapter 3: Language Basics – Conditionals

Chapter 3: Program Statements Notes

Control Flow:

  1. A conditional statement is sometimes called a selection statement.
  2. Each decision is based on a boolean expression.
  3. Three types of loop statements: while, do and for statements.

The if statement:

ifStatementFlowChart

Shorthand “if” statement: a ternary operator, inline if a or ternary

y = ( x <= 0 ) ? x : -x

which is a convenient way of writing

if ( x <= 0 )

y = x; else y = -x …..
  1. Equality operators
  2. Relational operators
equalityRelationOps The if-else statement: ifElseStatemtFC Nested if statements:
if (a < b)
   if (a < c)
      x = a;
   else
      x = c;
else
   if (b < c)
      x = b;
   else
      x = c;

Classwork: you can use this code snippet to write a program minMax_YI.java to prompt the user for three numbers and displays them in order from smallest to largest.Write the test/driver program if you use OOD.
NOTE: Assume the numbers are different. Include this assumption in your documentation.

Boolean expressions:

Logical operators:

logicalOps

Truth Table:

truthTable

Logical AND and OR operators:

andOrTruthTable

 

Example of truth table for a specific condition:

truthTableExample

 

Booelean Expression Exercise: Work on this boolean expression using the table attached here Builtintypestruthtable2
. Visit Canvas to access the doc version.

While Statement:

whileLoopFC

while ( condition )
{
   // statements block
}

A common mistake: an infinite loop. The loop will keep going forever.

whileStatmt

The do loop:

doFC

do
{
   // statements block
}
while ( condition );

The for loop:

forStatement

forFlowChart

for ( initialization; condition; update )
    {
      // block statements
    }

It is a sign of unbelievably bad taste to put unrelated conditions into the loop. ( lol )

Assignment:
Using the code snippet from the lesson write a program MinMax_YI.java to prompt the user for three numbers and displays them in order from smallest to largest. OOP is not required. However, write the test/driver program if you use OOD.

Assignment: Programming Project 3.2
Design and implement an application that reads an integer value representing a year input by the user. The purpose of the program is to determine if the year is a leap year (and therefore has 29 days in February) in the Gregorian calendar. A year is a leap year if it is divisible by 4 unless it is also divisible by 100 but not 400. For example, the year 2003 is not a leap year, but 2004 is. The year 1900 is not a leap year because it is divisible by 100, but the year 2000 is a leap year because even though it is divisible by 100, it is also divisible by 400. Produce an error message for any input value less than 1582 (the year the Gregorian calendar was adopted).

Reading and Writing Assignments:

Read pages 124 through 140, submit the short answers 3.1 through 3.5.

Short Answers:

3.1 What happens in the MinOfThree program if two or more of
the values are equal? If exactly two of the values are equal, does
it matter whether the equal values are lower or higher than the
third?

3.2 What is wrong with the following code fragment? Rewrite it so
that it produces correct output.

if (total == MAX)
    if (total < sum)
       System.out.println ("total == MAX and is < sum.");
    else
       System.out.println ("total is not equal to MAX");

3.3 What is wrong with the following code fragment? Will this code
compile if it is part of a valid program? Explain.

if (length == MIN_LENGTH)
   System.out.println ("The length is minimal.");

3.4 What output is produced by the following code fragment?

int num = 87, max = 25;
if (num >= max*2)
System.out.println ("apple");
System.out.println ("orange");
System.out.println ("pear");

3.5 What output is produced by the following code fragment?

int limit = 100, num1 = 15, num2 = 40;
if (limit <= limit)
{
if (num1 == num2)
System.out.println ("lemon");
System.out.println ("lime");
}
System.out.println ("grape");

Chapter 3 – Rock-paper-scissors

Classwork:
Homework review

Classwork/Homework
Design and implement an application that plays the rock-paper-scissors game against the computer. When played between two people, each person picks one of three options (usually shown by a hand gesture) at the same time, and a winner is determined. In the game, rock beats scissors, scissors beats paper, and paper beats rock. The program should randomly choose one of the three options (without revealing it), then ask for the user’s selection. At that point, the program reveals both choices and prints a statement indicating that the user won, that the computer won, or that it was a tie. Keep playing until the user chooses to stop, then print the number of user wins, losses, and ties.

rockpaperscissor

screen-shot-2016-09-20-at-6-46-04-pm

Chapter 3 – Conditionals – logical operators and truth tables

Chapter 3: Program Statements Notes

Control Flow:

  1. A conditional statement is sometimes called a selection statement.
  2. Each decision is based on a boolean expression.
  3. Three types of loop statements: while, do and for statements.

The if statement:

ifStatementFlowChart

Shorthand “if” statement: a ternary operator, inline if (iif) or ternary if

y = ( x >= 0 ) ? x : -x

which is a convenient  way of writing

if ( x >= 0 )
   y = x;
else
   y = -x

…..

  1. Equality operators
  2. Relational operators

equalityRelationOps

The if-else statement:

ifElseStatemtFC

Nested if statements:

nestedifs

Boolean expressions:

Logical operators:

logicalOps

Truth Table:

truthTable

Logical AND and OR operators:

andOrTruthTable

 

Example of truth table for a specific condition:

truthTableExample

 

 

 

Chapter 3 – Test Review

Homework:

edmodo.com
Self-Review questions
Short Answers 3.17 through 3.19

Chapter 3 Test Review
Review from the book the following material:
The “if” statement
Block Statement
Selection operator: ternary if
Brace layout
Indentation and tabs
Conditions with side effects
The “switch” statement
The “dangling” else
https://www.cs.umd.edu/~clin/MoreJava/ControlFlow/dangling.html
Boolean expressions
Multiple Relational operators
Confusing && and || conditions
Lazy evaluation of Boolean operators