Check edmodo.com for a new assignment.
Category Archives: Homework
Conditionals: Car Loan
Classwork/Homework:
-
- Write a java program CarLoan_YI.java to print a table giving the total amount paid and the remaining principal after each monthly payment.
- Prompt the user for the amount, interest and number of years.
- The prompt should include relevant messages so the user understands the input format.
- One of your runs should be with the data given below.
NOTE: your program properly handles an interest rate of 0% and avoids dividing by 0.
Click on the image to understand the formula
Example output:
Amount borrowed = 1000.00
Number of years = 2Interest rate = 3.00
Monthly payments = 42.98
Total interest = 31.55
If the total interest is pre-paid here is a chart:Month Amt Paid Remaining 1 42.98 957.02 2 85.96 914.04 3 128.94 871.06 4 171.92 828.08 5 214.91 785.09 6 257.89 742.11 7 300.87 699.13 8 343.85 656.15 9 386.83 613.17 10 429.81 570.19 11 472.79 527.21 12 515.77 484.23 13 558.76 441.24 14 601.74 398.26 15 644.72 355.28 16 687.70 312.30 17 730.68 269.32 18 773.66 226.34 19 816.64 183.36 20 859.62 140.38 21 902.61 97.39 22 945.59 54.41 23 988.57 11.43
If the total interest if included in the monthly payments, here is a chart:
Courtesy from Diane Li
/** Input/Output: Enter the loan amount in dollars: 1000 Enter the loan term in years: 2 Enter the annual interest rate as a percentage: 3 Month Amount Paid Remaining 1 42.98 988.56 2 85.96 945.58 3 128.94 902.60 4 171.92 859.62 5 214.90 816.64 6 257.88 773.66 7 300.86 730.68 8 343.84 687.69 9 386.83 644.71 10 429.81 601.73 11 472.79 558.75 12 515.77 515.77 13 558.75 472.79 14 601.73 429.81 15 644.71 386.83 16 687.69 343.84 17 730.68 300.86 18 773.66 257.88 19 816.64 214.90 20 859.62 171.92 21 902.60 128.94 22 945.58 85.96 23 988.56 42.98 24 1031.54 0.00 **/
Even though this chart doesn’t reflect the finance charge, it is an effective way to show the amount paid and the remaining values. In some cases, the finance charge is paid up front.
Optional
Car Loans | How Does Car Loan Interest Work? | IFS How does car loan interest affect you? Most car loans use simple interest. Learn more about car loan interest – it could save you money. Source: www.ifsautoloans.com/car-loan-interest/ If you really want the challenge of using the amortization model here is a chart that can show the effect of how the interest charges decrease as the amount borrowed also decreases.
- Write a java program CarLoan_YI.java to print a table giving the total amount paid and the remaining principal after each monthly payment.
Conditionals: CompoundIntTable_YI.java – Needs fixing
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.
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
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?
Conditionals: Asterisks
Asterisks Pattern
If you are finished with yesterday’s programming assignment, work on the following assignment.
Write a program, Asterisks_YI.java that prints the following pattern separately, one below the other each pattern separated front he next by one blank line. Use nested for loops ONLY to generate the patterns. All asterisks (*) should be printed by a single statement
which causes the asterisks to print side by side separated by a space.
Hint: The last two patterns require that each line begin with an appropriate number of blanks.
Extra Credit: Combine your code from the four separate problems into a single program that prints all four patterns side by side by making clever use of nested for loops. For all parts of this program – minimize the number of statements that print these characters.
/** * 4 patterns using asterisks * Basic program to start with * It draws a square of asterisks * * @mrs.e * @11/19/19 */ public class Asterisks { public static void main(String args[]) { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { System.out.print("* "); } System.out.println(); } } } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Input/Output: StdDraw Exercises
MyTriangles_YI.java
Use StdDraw to implement MyTriangles_YI.java to create a drawing of 3 different triangles: acute, obtuse, and right. Look at this example.
MyFunctionGraph_YI.java
Run and understand how FunctionGraph.java works and modify it to create the graph of this function
y = sin(4x) + cos(20x)
Write a short paragraph about how the graph changes as the input argument changes.
<pre>
/****************************************************************************** * Compilation: javac FunctionGraph.java * Execution: java FunctionGraph n * Dependencies: StdDraw.java * * Plots the function y = sin(4x) + sin(20x) between x = 0 and x = pi * by drawing n line segments. * ******************************************************************************/ public class FunctionGraph { public static void main(String[] args) { // number of line segments to plot int n = Integer.parseInt(args[0]); // the function y = sin(4x) + sin(20x), sampled at n+1 points // between x = 0 and x = pi double[] x = new double[n+1]; double[] y = new double[n+1]; for (int i = 0; i <= n; i++) { x[i] = Math.PI * i / n; y[i] = Math.sin(4*x[i]) + Math.sin(20*x[i]); } // rescale the coordinate system StdDraw.setXscale(0, Math.PI); StdDraw.setYscale(-2.0, +2.0); // plot the approximation to the function for (int i = 0; i < n; i++) { StdDraw.line(x[i], y[i], x[i+1], y[i+1]); } } } </pre>
Mystery Graph
Download the text file below and find out what the points draw.
Is the file missing anything?
Take a screenshot for submission.
Hint: use the PlotFinder.java
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: Running Java Programs and errors
Input/Output: Lesson Questions
Classwork: PU Input and Output Standard classes
You can get the following files from edmodo.com. Add them to your workspace:
StdIn.java
StdOut.java
StdDraw.java
StdAudio.java
-
- What is an abstraction?
- What is an input/output abstraction?
- What is an abstraction describing something having no limit?
- What is an abstraction for an infinite output sequence?
- What are the components of the improved input-output abstraction?
- What is an abstraction for an infinite input sequence?
7. What is an abstraction for an infinite output sequence?
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?
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.
15. How many spaces are printed before the digit 3 in the following line: StdOut.printf(“%8.3f”, Math.PI);?
Input/Output: Plot Filter
More on re-directing input/output
- 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(); } }
- 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
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