Category Archives: Classwork

Input/Output: Drawing Basics

Classwork: PU Input and Output Standard classes

Book site

Lesson’s pdf

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

Make sure these classes are located in your project.

StdIn.java read numbers and text from standard input
StdOut.java write numbers and text to standard output
StdDraw.java draw geometric shapes in a window

https://introcs.cs.princeton.edu/java/stdlib/

Answer the following questions:
1. Where is the center of the circle you drew?
2. What is the diameter of your circle?
3. Where is the center of the square you drew?
4. What is the length of the side of your square?

  • Outline and filled shapes. StdDraw also includes methods to draw circles, rectangles, and arbitrary polygons. Each shape defines an outline. When the method name is just the shape name, that outline is traced by the drawing pen. When the method name begins with filled, the named shape is instead filled solid, not traced.

    Standard drawing API: shapes

    The arguments for circle() define a circle of radius r; the arguments for square() define a square of side length 2r centered on the given point; and the arguments for polygon() define a sequence of points that we connect by lines, including one from the last point to the first point.

    Standard drawing shapes

  • Text and color. To annotate or highlight various elements in your drawings, StdDraw includes methods for drawing text, setting the font, and setting the the ink in the pen.

    Standard drawing text and color commands

    In this code, java.awt.Font and java.awt.Color are abstractions that are implemented with non-primitive types that you will learn about in Section 3.1. Until then, we leave the details to StdDraw. The default ink color is black; the default font is a 16-point plain Serif font.

  • Double buffering. StdDraw supports a powerful computer graphics feature known as double buffering. When double buffering is enabled by calling enableDoubleBuffering(), all drawing takes place on the offscreen canvas. The offscreen canvas is not displayed; it exists only in computer memory. Only when you call show() does your drawing get copied from the offscreen canvas to the onscreen canvas, where it is displayed in the standard drawing window. You can think of double buffering as collecting all of the lines, points, shapes, and text that you tell it to draw, and then drawing them all simultaneously, upon request. One reason to use double buffering is for efficiency when performing a large number of drawing commands.
  • Computer animations. Our most important use of double buffering is to produce computer animations, where we create the illusion of motion by rapidly displaying static drawings. We can produce animations by repeating the following four steps:
    • Clear the offscreen canvas.
    • Draw objects on the offscreen
    • Copy the offscreen canvas to the onscreen canvas.
    • Wait for a short while.

    In support of these steps, the StdDraw has several methods:

    Standard drawing animation commands


    The “Hello, World” program for animation is to produce a black ball that appears to move around on the canvas, bouncing off the boundary according to the laws of elastic collision. Suppose that the ball is at position (xy) and we want to create the impression of having it move to a new position, say (x + 0.01, y + 0.02). We do so in four steps:

    • Clear the offscreen canvas to white.
    • Draw a black ball at the new position on the offscreen canvas.
    • Copy the offscreen canvas to the onscreen canvas.
    • Wait for a short while.

    To create the illusion of movement, BouncingBall.java iterates these steps for a whole sequence of positions of the ball.

    Bouncing ball

  • Images. Our standard draw library supports drawing pictures as well as geometric shapes. The command StdDraw.picture(x, y, filename) plots the image in the given filename (either JPEG, GIF, or PNG format) on the canvas, centered on (x, y). BouncingBallDeluxe.java illustrates an example where the bouncing ball is replaced by an image of a tennis ball.
  • User interaction. Our standard draw library also includes methods so that the user can interact with the window using the mouse.
    double mouseX()          return x-coordinate of mouse
    double mouseY()          return y-coordinate of mouse
    boolean mousePressed()   is the mouse currently being pressed?
    
    • A first example. MouseFollower.java is the HelloWorld of mouse interaction. It draws a blue ball, centered on the location of the mouse. When the user holds down the mouse button, the ball changes color from blue to cyan.
    • A simple attractor. OneSimpleAttractor.java simulates the motion of a blue ball that is attracted to the mouse. It also accounts for a drag force.
    • Many simple attractors. SimpleAttractors.java simulates the motion of 20 blue balls that are attracted to the mouse. It also accounts for a drag force. When the user clicks, the balls disperse randomly.
    • Springs. Springs.java implements a spring system.

Standard audio.

 StdAudio is a library that you can use to play and manipulate sound files. It allows you to play, manipulate and synthesize sound.

Standard audio API

We introduce some some basic concepts behind one of the oldest and most important areas of computer science and scientific computing: digital signal processing.

    • Concert A. Concert A is a sine wave, scaled to oscillate at a frequency of 440 times per second. The function sin(t) repeats itself once every 2π units on the x-axis, so if we measure t in seconds and plot the function sin(2πt × 440) we get a curve that oscillates 440 times per second. The amplitude (y-value) corresponds to the volume. We assume it is scaled to be between −1 and +1.
    • Other notes. A simple mathematical formula characterizes the other notes on the chromatic scale. They are divided equally on a logarithmic (base 2) scale: there are twelve notes on the chromatic scale, and we get the ith note above a given note by multiplying its frequency by the (i/12)th power of 2.

      Musical notes, numbers, and waves

      When you double or halve the frequency, you move up or down an octave on the scale. For example 880 hertz is one octave above concert A and 110 hertz is two octaves below concert A.

    • Sampling. For digital sound, we represent a curve by sampling it at regular intervals, in precisely the same manner as when we plot function graphs. We sample sufficiently often that we have an accurate representation of the curve—a widely used sampling rate is 44,100 samples per second. It is that simple: we represent sound as an array of numbers (real numbers that are between −1 and +1).
      Sampling a sine wave at various rates             Sampling a sine wave at 44,100 Hertz

      For example, the following code fragment plays concert A for 10 seconds.

      int SAMPLING_RATE = 44100;
      double hz = 440.0;
      double duration = 10.0;
      int n = (int) (SAMPLING_RATE * duration);
      double[] a = new double[n+1];
      for (int i = 0; i <= n; i++) {
         a[i] = Math.sin(2 * Math.PI * i * hz / SAMPLING_RATE); 
      }
      StdAudio.play(a); 
      

  • Play that tune. PlayThatTune.java is an example that shows how easily we can create music with StdAudio. It takes notes from standard input, indexed on the chromatic scale from concert A, and plays them on standard audio.

https://introcs.cs.princeton.edu/java/15inout/

https://introcs.cs.princeton.edu/java/stdlib/

https://java.mrseliasclasses.org/pu-input-and-output/

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: The Standard Draw Class

Create a new folder in your Java folder, Unit_2.

Create a new project in Unit_2, InputOutput or InOut

Add the available StdLib classes to your project via the Edit tab, drag them or create them in your project.

Your project you look like this:

Let’s test our project with this program:

NOTE: include documentation and attach the image (screenshot)

/**
 * Write a description of class Triangle here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Triangle
{
    public static void main(String args[])
    {
        StdDraw.line(0,0,.1,.1);
        StdDraw.line(0,0,0,1);
        StdDraw.line(0,0,1,0);
    }
}
   


Input/Output: Drawing Random Circles

Write a program Circles_YI.java that draws filled circles of random size at random positions in the unit square, producing images like those below. Your program should take four command-line arguments: the number of circles, the probability that each circle is black, the minimum radius, and the maximum radius.

random circles

Submit screenshots and submit them.

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

Input/Output: Graph Paper

Screen Shot 2015-02-23 at 12.19.21 AM

Classwork:
Write a program, MyGraphPaper_YI.java similar to CheckerBoard.java from below but to draw 2 different kinds of graph paper. Think of what graph paper you would use in a math class.

Study program CheckerBoard.java that takes a command-line argument N and plots an N-by-N checkerboard with red and black squares. It colors the lower left square red.

[spoiler title=’Checkerboard.java’]
Below is the syntax highlighted version of Checkerboard.java from §1.5 Input and Output.

/******************************************************************************
 *  Compilation:  javac Checkerboard.java 
 *  Execution:    java Checkerboard n
 *  Dependencies: StdDraw.java
 *
 *  Plots an n-by-n checkerboard.
 *
 ******************************************************************************/

public class Checkerboard { 

    public static void main(String[] args) { 
        int n = Integer.parseInt(args[0]);
        StdDraw.setXscale(0, n);
        StdDraw.setYscale(0, n);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if ((i + j) % 2 != 0) StdDraw.setPenColor(StdDraw.BLACK);
                else                  StdDraw.setPenColor(StdDraw.RED);
                StdDraw.filledSquare(i + 0.5, j + 0.5, 0.5);
            }
        }
    }

}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne. 
Last updated: Fri Oct 20 14:12:12 EDT 2017.

[/spoiler]


RandomBlock_YI.java Animation
Use the tools from the BouncingBall program to implement RandomBlock_YI.java. This program re-uses the program from the graph paper assignment and randomly select squares on the grid that will become a solid color or “alive” and then randomly it will become back to white or “dead” again.

Input/Output: printf

 

Java’s print() and println() methods are the ones that you have been using. The printf() method gives us more control over the appearance of the output.

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

Format strings begin with % and end with a one-letter conversion code. The following table summarizes the most frequently used codes:

  • Format string. The format string can contain characters in addition to those for the conversion specification. The conversion specification is replaced by the argument value (converted to a string as specified) and all remaining characters are passed through to the output.
  • Multiple arguments. The printf() function can take more than two arguments. In this case, the format string will have an additional conversion specification for each additional argument.

Here is more documentation on printf format string syntax

[spoiler title=’TestPrintf’]

public class TestPrintf
{
   public static void main(String [] args)
   {
       System.out.println("123456789012345678901234567890");
       System.out.printf("%10.2f%8.2f",3.33333, 1234.5677865);
       System.out.println();
       for (int i = 0; i < 12; i++){
        System.out.printf("%2d%6d",i, i*i);
        System.out.println();
    }
        
    }
}

/**
123456789012345678901234567890
      3.33 1234.57
 0     0
 1     1
 2     4
 3     9
 4    16
 5    25
 6    36
 7    49
 8    64
 9    81
10   100
11   121

 */

[/spoiler]

 

Input/Output: Graphics: CircleGradient.java and Gray

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

Classwork:

Remember to work on the current assignments before you work on this assignment.

Write a program, YI_CircleGradient.java to draw the following:
gradientcircle

Extra credit:
Write an animation program, YI_GrayGradient3D.java that shows the image below but the whitish to blackish region follows the mouse as the mouse moves over the ball.
graygradient3D