Category Archives: Lesson

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 – 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

Chapter 3: Comparing Characters – Strings – floating-point numbers

Chapter 3: More Notes

The switch Statement

Comparing Characters and Strings

if (ch1 > ch2)
   System.out.println (ch1 + " is greater than " + ch2);
else
   System.out.println (ch1 + " is NOT greater than " + ch2);


In the Unicode character set all lowercase alphabetic characters (‘a’ through ‘z’ ) are in alphabetical order. The same is true of uppercase alphabetic characters ( ‘A’ through ‘Z’ ) and digits ( ‘0’ through ‘9’ ). The digits come before the uppercase alphabetic characters,
which come before the lowercase alphabetic characters.

Assuming that namel and name2 are String objects

if (namel.equals(name2))
   System.out.println ("The names are the same.");
else
   System.out.println ("The names are not the same.");


int result = namel.compareTo(name2); 
if (result < 0)
   System.out.println (namel + " comes before II + name2); 
else
   if (result == 0)
      System.out.println ("The names are equal.");
   else
      System.out.println (namel + " follows" + name2);


Keep in mind that comparing characters and strings is based on the Unicode character set. This is called a lexicographic ordering. If all alphabetic characters are in the same case (upper or lower), the lexicographic ordering will be alphabetic.

However, when comparing two strings, such as “able” and “Baker”, the compareTo method will conclude that “Baker” comes first because all of the uppercase letters come before all of the lowercase letters Unicode character set.

A string that is the prefix of another, longer string is considered to precede the longer string. For example, when comparing two strings such as “horse” and “horsefly”, the compareTo method will conclude that “horse” comes first.

comparing floating point values

if (Math.abs(f1 - f2) < TOLERANCE)
   System.out.println ("Essentially equal.");         


The value of the constant TOLERANCE should be appropriate for the situation.

More Operators

Pre and Post unary operators

Increment: i++ and ++i
Decrement: i- – and – -i

Assignment Operator
assignments

Programming Project 3.3
Change the solution to the Programming Project 3.2 so that the user can enter more than one year. Let the user end the program by entering a sentinel value. Validate each input value to make sure it is greater than or equal to 1582.

Chapter 3: Comparing Floating Point Numbers

Comparing Floating-Point Numbers
Floating-point numbers have only limited precision, and calculations can introduce roundoff errors. Take a look at this example:

double r = Math.sqrt(2);
double d = r * r - 2;
if ( d == 0 )
   System.out.println(" sqrt(2) squared minus 2 is 0");
else
   System.out.println(" sqrt(2) squared minus 2 is not 0 but " + d);

When comparing floating-point numbers, don’t test for equality.
Instead, check whether they are close enough.
In Java, we program the test as follows: x is close to 0 if
Math.abs(x) ≤ EPSILON
where we define

final double EPSILON = 1E-14;

Similarly, you can test whether two numbers are close to each other by checking whether their difference is close to 0.
| x – y | ≤ ε
However, this is not always good enough. Suppose x and y are rather large, say a few billion each. Then they could be the same, except for a roundoff error, even if their difference was quite a bit larger than 10^(-14)
To overcome this problem, you need to divide by the magnitude of the numbers before comparing how close they are. Here is the formula: x and y are close enough if

     
      | x - y |
    ------------  ≤ ε
     max(|x|,|y|)

The choice of EPSILON depends on your application. Let’s take a look at one possible value:

final double EPSILON = 1E-14;
Math.abs( x - y ) / Math.max(Math.abs( x ), Math.abs( y )) <= EPSILON;

 
Assignments:

1. What EPSILON would you choose to find out if these two pair of values are relatively equal?
Show your calculations and how you determine if they are equal or not. This is dependent on the application. Justify your EPSILON.

Are 1,000,000 and 1,000,001 equal?
Are 0.0000002 and 0.0000003 equal?

Is there one EPSILON that fits all expressions?

2. Write a program, FloatCompare_YI.java that reads in two floating-point numbers and tests (a) whether they are the same when rounded to two decimal places and (b) whether they differ by less than 0.01. Here are two sample runs.
Enter two floating-point numbers:
2.0
1.99998
They are the same when rounded to two decimal places. They differ by less than 0.01.
Enter two floating-point numbers:
0.999
0.991
They are different when rounded to two decimal places. They differ by less than 0.01.

3. Write a program that prints all real solutions to the quadratic equation
ax² + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b² - 4ac is negative, display a message stating that there are no real solutions.
Implement a class QuadFormula_YI whose constructor receives the coefficients a, b, c of the quadratic equation. Supply methods getSolution1 and getSolution2 that get the solutions, using the quadratic formula.
Supply two methods

       boolean hasSolutions()

returns false if the discriminant is negative.

       boolean oneRealSolution()

returns false if the discriminant is negative. Implement this method using EPSILON to determine if discriminant is zero.

 

Chapter 2: Programming: Telephone Numbers with PDT and ADT

Chapter 2: Objects and Primitive Data Types

  1. Write a java application, TelephoneNumV1_YI.java that creates and prints a random phone number of the form XXX-XXX-XXXX. Include the dashes in the output. Do not let the first three digits contain an 8 or 9 (but don’t be more restrictive than that), and make sure that the second set of three digits is not greater than 742.
    Hint: Think through the easiest way to construct the phone number. Each digit does not have to be determined separately.

  2. Write an Object Oriented Application, TelephoneV2_YI.java with the same functionality as the previous version but using Object Oriented Design.

Project: NBody Simulation

May 15th, 2015

Screen Shot 2015-05-12 at 11.47.35 AM

Using PU Classes:
Programming Assignment due on 5/29: N-Body Simulation
Screen Shot 2015-05-13 at 1.47.10 PM

Checklist

Some cool links:
Screen Shot 2015-05-13 at 1.54.01 PM

Screen Shot 2015-05-13 at 1.55.27 PM

Screen Shot 2015-05-13 at 1.57.08 PM


Some math and little bit of physics:

AP Exam Review: Concepts Refresher

May 1st, 2015
Screen Shot 2014-09-17 at 12.56.56 PM

Classwork and Homework posted on edmodo.com
Lab review questions.
AP Exam 2009, questions 1, 3 and 4.

Concepts Refresher:

Screen Shot 2015-04-30 at 9.11.51 PM
Default Constructor:
The default constructor is the no-argument constructor automatically generated unless you define another constructor. It initialises any uninitialised fields to their default values. For your example, it would look like this assuming that the types are String, int and int:


public Module()
{
  super();
  this.name = null;
  this.credits = 0;
  this.hours = 0;
}

This is exactly the same as


public Module()
{}

And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.

Screen Shot 2015-04-30 at 9.26.09 PM

Method Overloading and Method Overriding.

1) In Method Overloading your method calls to the methods are decided by the compiler in the sense that which function is going to be called is decided by your compiler at compile time. Hence being EARLY BINDING.

2) In method Overriding, it is decided at RUNTIME which method is going to be called. So it is reffered as LATE BINDING.

The Magpie Lab 2

March 23rd, 2015

The Magpie Chatbot Lab
Visit edmodo.com for the student guide.

Screen Shot 2015-03-23 at 12.57.30 AM

Classwork:
Exploration
Have several conversations with your chatbot and answer the following questions:
• How does it respond to “where do you come from”?
• What is the most interesting response?
• What is the most peculiar response?
• How does it respond to “asdfghjkl;”? Exercises
Work with another group and have two different chatbots converse with each other.

Homework:
2 Questions
Simple chatbots act by looking for key words or phrases and responding to them.
1. Can you identify keywords to which your chatbot responds?
2. Think of several keywords and the responses they might cause.