Category Archives: Lesson

Conditionals: if if/else flowcharts

New topic: Conditionals
Click on this label:
Screen Shot 2014-10-02 at 10.05.29 AM

Classwork:
Flowcharts: write a short code fragment for each of the following flowcharts:
if and if/else
flowchars-if-else

while and for loops

flowchart-loop

More on conditionals with the slides on this link:

Assignments:

  1. Write a more general and robust version of ComplexRootsQuad.java that prints the roots of the polynomial ax^2 + bx + c, prints real and complex solutions.
  2. What (if anything) is wrong with each of the following statements?
    if (a > b) then c = 0;
    if a > b { c = 0; }
    if (a > b) c = 0;
    if (a > b) c = 0 else b = 0;
  3. Write a code fragment that prints true if the double variables x and y are both strictly between 0 and 1 and false otherwise.
  4. Write a program AllEqual_YI.java that takes three integer command-line arguments and prints equal if all three are equal, and not equal otherwise.
  5. Rewrite TenHellos.java to make a program ManyHellos_YI.java that prompts the user for the consecutive lines to print… You may assume that the argument is less than 1000. Hint: consider using i % 10 and i % 100 to determine whether to use “st”, “nd”, “rd”, or “th” for printing the ith Hello.Example output:
    * Starting number? 4
    * Ending number? 8

    * 4th Hello
    * 5th Hello
    * 6th Hello
    * 7th Hello
    * 8th Hello

  6. What is the value of m and n after executing the following code?
    int n = 123456789;
    int m = 0;
    while (n != 0) {
       m = (10 * m) + (n % 10);
       n = n / 10;
    }
    
    
  7. What does the following code print out?
    int f = 0, g = 1;
    for (int i = 0; i <= 15; i++) {
       System.out.println(f);
       f = f + g;
       g = f - g;
    }
    
    

A site to check your understanding:


Conditionals: Ex 1-7

Screen Shot 2014-09-23 at 10.00.31 AM

Classwork:
1. Write a more general and robust version of YI_Quadratic.java that prints the roots of the polynomial ax^2 + bx + c, prints an appropriate error message if the discriminant is negative, and behaves appropriately (avoiding division by zero) if a is zero.

  1. What (if anything) is wrong with each of the following statements?
    if (a > b) then c = 0;
    if a > b { c = 0; }
    if (a > b) c = 0;
    if (a > b) c = 0 else b = 0;

  2. Write a code fragment that prints true if the double variables x and y are both strictly between 0 and 1 and false otherwise.

Homework: Conditionals and loops
4. Write a program YI_AllEqual.java that takes three integer command-line arguments and prints equal if all three are equal, and not equal otherwise.

  1. Rewrite YI_TenHellos.java to make a program YI_Hellos.java that takes the number of lines to print as a command-line argument. You may assume that the argument is less than 1000. Hint: consider using i % 10 and i % 100 to determine whether to use “st”, “nd”, “rd”, or “th” for printing the ith Hello.

  2. What is the value of m and n after executing the following code?

int n = 123456789;
int m = 0;
while (n != 0) {
   m = (10 * m) + (n % 10);
   n = n / 10;
}

  1. What does the following code print out?
int f = 0, g = 1;
for (int i = 0; i <= 15; i++) {
   System.out.println(f);
   f = f + g;
   g = f - g;
}

Conditionals: Simple Interest

Screen Shot 2014-09-23 at 10.00.31 AM

Write a program, SimpleInterest_YI.java that uses a while loop to calculate how many years it would take to have at least $1,100 at an interest rate of 1.2% when $1,000 is deposited in a savings bank account. DO NOT USE THE FORMULA.

stack-of-money

Simple interest is money you can earn by initially investing some money (the principal). A percentage (the interest) of the principal is added to the principal, making your initial investment grow!

As part of your program include the calculation done with the formula.

An example of Simple Interest

Conditionals: CompoundIntTable_YI.java – Needs fixing

Screen Shot 2014-09-23 at 10.00.31 AM

NO MORE MAGIC NUMBERS

Things to keep in mind when submitting your work:
1. Copy and paste your program in the post.
2. Attach your file(s).
3. Make sure your program has a header and the input/output.
4. If your program doesn’t run, an explanation should be the first line in the post.

Screen Shot 2014-09-28 at 12.38.49 PM

Classwork:
YI_CompoundIntTable.java: Use a while loop to show how the investment increases as the accumulated total becomes at least $1,100 at an interest rate of 1.2% when $1,000 is deposited in a savings bank account.

The table should have the following columns:


year      accum interest/year          total accumulated up to this year  
 1        12.0                         1012.0
 2        24.14                        1024.14
 3        36.43                        1036.43
...

Number of years for the investment of $1000 to reach at least a value of $1,100 with an interest rate of 1.2% is  8

Homework:
CompIntCompareTable_YI.java: Create another table that compares how you use the formula P(1+r)^t, where t is the number of years and how your program calculates the equivalent values.
End up your assignment with a conclusion about the similarities and the differences between the two approaches.

Conditionals: Monty Hall

monty-hall

Assignment:
Game simulation.
In the game show Let’s Make a Deal, a contestant is presented with three doors. Behind one door is a valuable prize, behind the other two are gag gifts. After the contestant chooses a door, the host opens up one of the other two doors (never revealing the prize, of course).

The contestant is then given the opportunity to switch to the other unopened door. Should the contestant do so? Intuitively, it might seem that the contestant’s initial choice door and the other unopened door are equally likely to contain the prize, so there would be no incentive to switch. Write a program MonteHall_YI.java to test this intuition by simulation.

Your program should take an integer command-line argument n, play the game n times using each of the two strategies (switch or don’t switch) and print the chance of success for each strategy.

End the program with a message stating the conclusion: Is a bigger chance of winning if you switch to a different door?

Input/Output: Redirection and piping

Using the StdIn in Terminal

Typing input. When you use the java command to invoke a Java program from the command line, you actually are doing three things:

(1) issuing a command to start executing your program,

(2) specifying the values of the command-line arguments, and

(3) beginning to define the standard input stream. The string of characters that you type in the terminal window after the command line is the standard input stream.

For example, AddInts.java takes a command-line argument n, then reads n numbers from standard input and adds them, and prints the result to standard output:

/******************************************************************************
 *  Compilation:  javac AddInts.java
 *  Execution:    java AddInts
 *  Dependencies: StdIn.java StdOut.java
 *  
 *  This program takes a command-line argument n, reads in n integers,
 *  and prints out their sum.
 *
 *  % java AddInts n
 *
 ******************************************************************************/

public class AddInts { 
    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);
        int sum = 0;
        for (int i = 0; i < n; i++) {
            int value = StdIn.readInt();
            sum = sum + value;
        }
        StdOut.println("Sum is " + sum);
    }
}

Input format. If you type abc or 12.2 or true when StdIn.readInt() is expecting an int, then it will respond with an InputMismatchException. StdIn treats strings of consecutive whitespace characters as identical to one space and allows you to delimit your numbers with such strings.

Interactive user input. TwentyQuestions.java is a simple example of a program that interacts with its user. The program generates a random integer and then gives clues to a user trying to guess the number. The fundamental difference between this program and others that we have written is that the user has the ability to change the control flow while the program is executing.

/******************************************************************************
 *  Compilation:  javac TwentyQuestions.java
 *  Execution:    java TwentyQuestions
 *  Dependencies  StdIn.java
 *
 *  % java TwentyQuestions 
 *  I'm thinking of a number between 1 and 1,000,000 
 *  What's your guess? 500000 
 *  Too high 
 *  What's your guess? 250000 
 *  Too low 
 *  What's your guess? 375000 
 *  Too high 
 *  What's your guess? 312500 
 *  Too high 
 *  What's your guess? 300500 
 *  Too low 
 *  ... 
 *
 ******************************************************************************/

public class TwentyQuestions {

    public static void main(String[] args) {

        // Generate a number and answer questions
        // while the user tries to guess the value.
        int secret = 1 + (int) (Math.random() * 100);

        StdOut.print("I'm thinking of a number ");
        StdOut.println("between 1 and 100");
        int guess = 0; 
        while (guess != secret) {

            // Solicit one guess and provide one answer
            StdOut.print("What's your guess? ");
            guess = StdIn.readInt();
            if      (guess == secret) StdOut.println("You win!");
            else if (guess  < secret)  StdOut.println("Too low ");
            else if (guess  > secret)  StdOut.println("Too high");
        }
    }
} 


Redirection and piping

In terminal:

/******************************************************************************
 *  Compilation:  javac RandomSeq.java
 *  Execution:    java RandomSeq n
 *
 *  Prints n random real numbers between 0 and 1.
 *
 *  % java RandomSeq 5
 *  0.1654760343787165
 *  0.6212262060326124
 *  0.631755596883274
 *  0.4165639935584283
 *  0.4603525361488371
 *
 ******************************************************************************/

public class RandomSeq { 
    public static void main(String[] args) {

        // command-line argument
        int n = Integer.parseInt(args[0]);

        // generate and print n numbers between 0 and 1
        for (int i = 0; i < n; i++) {
            System.out.println(Math.random());
        }
    }
}

Redirecting standard output to a file

java RandomSeq 1000 > data.txt

This command will display data by a window of data at a time.
more < data.txt

Processing an arbitrary-size input stream. Typically, input streams are finite: your program marches through the input stream, consuming values until the stream is empty. But there is no restriction on the size of the input stream. Average.java reads in a sequence of real numbers from standard input and prints their average.

Redirecting standard output from a file

java Average < data.txt

/******************************************************************************
 *  Compilation:  javac Average.java
 *  Execution:    java Average < data.txt
 *  Dependencies: StdIn.java StdOut.java
 *  
 *  Reads in a sequence of real numbers, and computes their average.
 *
 *  % java Average
 *  10.0 5.0 6.0
 *  3.0 7.0 32.0
 *  
 *  Average is 10.5
 *
 *  Note  signifies the end of file on Unix.
 *  On windows use .
 *
 ******************************************************************************/

public class Average { 
    public static void main(String[] args) { 
        int count = 0;       // number input values
        double sum = 0.0;    // sum of input values

        // read data and compute statistics
        while (!StdIn.isEmpty()) {
            double value = StdIn.readDouble();
            sum += value;
            count++;
        }

        // compute the average
        double average = sum / count;

        // print results
        StdOut.println("Average is " + average);
    }
}

Connecting two programs
java RandomSeq 1000000 | java Average

Filters:
more allows you to display a window of data at a time:
java RandomSeq 1000 | more

Guess what this one does:
java RandomSeq 5 | sort

Note: Look at the book site for great illustrations on both redirection and piping.

Classwork:
Go to the Required Submission paragraph for specifics on how to turn in a copy of your terminal session on today’s classwork/activities.

Input/Output: Lesson Questions

Classwork: PU Input and Output Standard classes

Book site
Screen Shot 2015-02-23 at 12.19.21 AM

Lesson’s pdf
Screen Shot 2015-11-22 at 4.48.06 PM

You can get the following files from edmodo.com. Add them to your workspace:
StdIn.java
StdOut.java
StdDraw.java
StdAudio.java

    1. What is an abstraction?
    2. What is an input/output abstraction?
    3. What is an abstraction describing something having no limit?
    4. What is an abstraction for an infinite output sequence?
    5. What are the components of the improved input-output abstraction?
    6. What is an abstraction for an infinite input sequence?

stdIn

           7. What is an abstraction for an infinite output sequence?

StdOut

            8. These are the same as System.out. Why not just use System.out?

            9. Interactive input
                   • Prompt user to type inputs on standard input stream.
                   • Mix input stream with output stream.

            10. Average
                   • Read a stream of numbers.
                   • Compute their average.

            11. How do I specify the end of the stream?

            12. What is the limit on the size of the input stream?

            13. Do I always have to type in my input data and print my output?

pipingIO

             14. What can you do if there’s no room for a huge file on my computer?

Formatted printing basics again. In its simplest form, printf() takes two arguments. The first argument, a string, contains a format that describes how the second argument is to be converted to a string for output.
printfexample
printftable

15. How many spaces are printed before the digit 3 in the following line: StdOut.printf(“%8.3f”, Math.PI);?

Input/Output: Plot Filter

Screen Shot 2015-02-23 at 12.19.21 AM

More on re-directing input/output

  1. Include this PlotFilter in your project
    /******************************************************************************
     *  Compilation:  javac PlotFilter.java
     *  Execution:    java PlotFilter < input.txt
     *  Dependencies: StdDraw.java StdIn.java
     *  
     *  % java PlotFilter < USA.txt
     *
     *  Datafiles:    http://introcs.cs.princeton.edu/java/15inout/USA.txt
     *
     ******************************************************************************/
    
    public class PlotFilter { 
    
        public static void main(String[] args) {
    
            // read in bounding box and rescale
            double x0 = StdIn.readDouble();
            double y0 = StdIn.readDouble();
            double x1 = StdIn.readDouble();
            double y1 = StdIn.readDouble();
            StdDraw.setXscale(x0, x1);
            StdDraw.setYscale(y0, y1);
    
            // for bigger points
            StdDraw.setPenRadius(0.005);
    
            // to speed up performance, defer displaying points
            StdDraw.enableDoubleBuffering();
    
            // plot points, one at a time
            while (!StdIn.isEmpty()) {
                double x = StdIn.readDouble();
                double y = StdIn.readDouble();
                StdDraw.point(x, y);
            }
    
            // display all of the points now
            StdDraw.show();
    
        }
    }
    
    
  2. Create a text file with the data from the link below. Right-click on the middle of the page and “save as” in your project folder.
    USA.txt

Assignments:
Standard Drawing
usacities

Use the java programs from the lesson, Triangle.java, PlotFilter.java, and FunctionGraph.java to work on the assignments posted on edmodo.com.

MyPlotFilter_YI.java
Use PlotFilter.java from Filtering data to a standard drawing to create your own drawing.

Read about Standard drawing and the Methods Summary