Classwork:
Standard Drawing: Animation
Discussion on BouncingBall.java and Banner.java
Check on edmodo.com for assignment: CrossingBalls.java
Homework:
Check on edmodo.com for assignment: SongLyrics.java
StdAudio is a library that you can use to play and manipulate sound files. It allows you to play, manipulate and synthesize sound.
We introduce some some basic concepts behind one of the oldest and most important areas of computer science and scientific computing: digital signal processing.
Standard Drawing: Animation and images
Images. PU standard draw library supports drawing pictures as well as geometric shapes.
https://introcs.cs.princeton.edu/java/15inout/TennisBall.png https://introcs.cs.princeton.edu/java/15inout/pipebang.wav
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.
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.
- 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).
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.
Your first animation using java!!!
Standard Drawing: Animation and images Images.
/****************************************************************************** * Compilation: javac BouncingBall.java * Execution: java BouncingBall * Dependencies: StdDraw.java * * Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1). * * % java BouncingBall * ******************************************************************************/ public class BouncingBall { public static void main(String[] args) { // set the scale of the coordinate system StdDraw.setXscale(-1.0, 1.0); StdDraw.setYscale(-1.0, 1.0); StdDraw.enableDoubleBuffering(); // initial values double rx = 0.480, ry = 0.860; // position double vx = 0.015, vy = 0.023; // velocity double radius = 0.05; // radius // main animation loop while (true) { // bounce off wall according to law of elastic collision if (Math.abs(rx + vx) > 1.0 - radius) vx = -vx; if (Math.abs(ry + vy) > 1.0 - radius) vy = -vy; // update position rx = rx + vx; ry = ry + vy; // clear the background StdDraw.clear(StdDraw.GRAY); // draw ball on the screen StdDraw.setPenColor(StdDraw.BLACK); StdDraw.filledCircle(rx, ry, radius); // copy offscreen buffer to onscreen StdDraw.show(); // pause for 20 ms StdDraw.pause(20); } } } Copyright © 2000–2011, Robert Sedgewick and Kevin Wayne. Last updated: Tue Aug 30 09:58:33 EDT 2016.
Classwork:
Add this program to your current project.
Make the following changes, submit a screenshot for each change and the final program:
Classwork:
Write a program, BarGraph2_YI.java to create a bar graph with asterisks as in the previous bar graph. However, the array’s values are the raw data. Use this array and values, dataSet = { 67, 89, 55, 100, 95, 93, 57, 19, 88, 87, 86, 91,90}.
Output: 00-09: 10-19: * 20-29: 30-39: 40-49: 50-59: ** 60-69: * 70-79: 80-89: **** 90-99: **** 100: *
Do not use if statements to check if the value fall within a range.
HINT: What is the result of dividing each grade by 10?
WARNING: DO NOT USE if STATEMENTS!!! or WHILE LOOPS TO FIND THE RANGE OF THE GRADES!!!
Claswork/Homework:
Consider the following:
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the student cafeteria, with 1 being “awful” and 5 being “excellent.” Randomly assign 20 responses to an integer array and determine the frequency of each rating.
Using what you learned about the elements of an array as counters, write a program, FoodSurvey_YI.java to display the rating and their frequency in two well formatted columns.
Output example:
Rating Frequency 1: 10 2: 5 3: 2 4: 2 5: 1
Additional programming style guidelines:
/* * 1. Make sure your program has indentation when is needed. * 2. Please include a comment line about local variables and group them all * together at the top of the program as long as it is not an OOD program. * 3. Never create a new local variable inside a loop! * 4. Have a blank line between different parts of the program */
final int COUNTRIES = 7; final int MEDALS = 3; int[][] counts = new int[COUNTRIES][MEDALS];
or but not both:
int[][] counts = { { 1, 0, 1 }, { 1, 1, 0 }, { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 1 }, { 0, 1, 1 }, { 1, 1, 0 } };
for (int i = 0; i < COUNTRIES; i++) { // Process the ith row for (int j = 0; j < MEDALS; j++) { // Process the jth column in the ith row System.out.printf("%8d", counts[i][j]); } System.out.println(); // Start a new line at the end of the row }
for (int i = 0; i < counts.length; i++) { for (int j = 0; j < counts[0].length; j++) { System.out.printf("%8d", counts[i][j]); } System.out.println(); }
Accessing the neighboring elements of a 2D array
Adding by rows:
int total = 0; for (int i = 0; i < COUNTRIES; i++) { total = 0; for (int j = 0; j < MEDALS; j++) { total = total + counts[i][j]; } }
Adding by columns:
int total = 0; for (int j = 0; j < MEDALS; j++) { total = 0; for (int i = 0; i < COUNTRIES; i++) { total = total + counts[i][j]; } }
Classwork:
Write a program, MedalsTable_YI.java to produce the following output:
Assignment:
Consider as an example an 8 × 8 array for a board game:
int[][] board = new int[8][8];
BoardGame_YI.java: Using two nested loops, initialize the board using "for" loops so that zeroes and ones alternate, as on a checkerboard. Prompt the user for the size of the "square" 2D array and display the board on the screen.
0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 ... 1 0 1 0 1 0 1 0
Hint: Check whether i + j is even.
If you fold a square diagonally, you will create a right isosceles triangle. We will take the triangle’s area to be 1. Continue to halve this triangle again and again by placing the acute angles on top of each other. Write a java program, HalfAreas_YI.java and prompt the user how many times wants the square to be folded.
As an example, let’s say the user’s response to the prompt is 5.
Output: in full sentence display the number of folds and the area of the final triangle.
Find an origami paper on the last table and do it manually first. Do the calculations so you can check your program is doing the right thing.
Once you confirm your program is running properly, run the program for an input of 7 folds. Submit both, the hand calculation, the output for the test and the solution for the 7 folds.
NOTE: if you are aware of finding the solution by using a formula, you can add that information to your documentation. For this assignment you must use loops.
Implement an animation, RandomBlock_YI.java. The CheckerBoard.java can easily be changed to randomly select a random number of squares on the grid and become a solid color (“alive”) and then randomly it will turn back to white (“dead”) again.
Re-Use-Code: these are good resources for this assignment:
MyGraphPaper.java
BouncingBall.java
CheckerBoard.java
/****************************************************************************** * 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); } } } }
Classwork/Homework:
Here is the 5 × 5 square that you get if you follow this method:
Write a program, MagicNSquare_YI.java whose input is the number n and whose output is the magic square of order n if n is odd. Include the code to check the new array is in fact a Magic Square. Display the sum of the columns, rows and diagonals.
If a bank’s total assets are under a certain limit, the bank is unsafe. The money it borrowed cannot be returned to the lender, and the lender cannot count the loan in its total assets. Consequently, the lender may also be unsafe, if its total assets are under the limit. Write a program, BankFinancing_YI.java to find all the unsafe banks. Your program reads the input as follows. It first reads two integers n and limit, where n indicates the number of banks and limit is the minimum total assets for keeping a bank safe. It then reads n lines that describe the information for n banks with IDs from 0 to n-1.
The first number in the line is the bank’s balance, the second number indicates the number of banks that borrowed money from the bank, and the rest are pairs of two numbers. Each pair describes a borrower. The first number in the pair is the borrower’s ID and the second is the amount borrowed. For example, the input for the five banks in the figure is as follows (note that the limit is 201):
5 201 25 2 1 100.5 4 320.5 125 2 2 40 3 85 175 2 0 125 3 75 75 1 0 125 181 1 2 125
The total assets of bank 3 are (75 + 125), which is under 201, so bank 3 is unsafe. After bank 3 becomes unsafe, the total assets of bank 1 fall below (125 + 40). Thus, bank 1 is also unsafe. The output of the program should be
Unsafe banks are 3 1
(Hint: Use a two-dimensional array borrowers to represent loans. borrowers[i][j] indicates the loan that bank i loans to bank j. Once bank j becomes unsafe, borrowers[i][j] should be set to 0.)
If you are done with every assignment, here is the next topics
PU Input and Output Standard classes
Lesson’s pdf
Create a new project: InputOutput
You can get the following files from edmodo.com. Add them to your workspace: