Assignment

Critical Assignment Instructions and Recommendations

Do not start programming an assignment until you do three things:

  1. Read entire assignment up to hints, pay close attention to input/output specification. If you have problems completing assignment, consult hints.
  2. Document your program by using a standard header comment that clearly defines the assignment objectives. You can loose points by not having a properly commented header. Just cutting and pasting the assignment description is not only a good way to loose points but is a clear violation of intellectual property right/academic integrity.
  3. In comment header include specific input/output specifications.

All assignments will be graded using submit, however failure to properly document an assignment can result in points taken off. Consult Canvas Web-casts for correct comment structure. Nota bene, submit requires you do meet input/output specifications. All modern day large system are based on multiple components meeting I/O specifications. Assignments are due by dates specified on submit, you have a 7 day grace period that takes off 20-25%, after that you can submit assignments at a 50% penalty.

Canvas is blocking some links, if link doesn't open, use right^click open in new tab.

Intro Orientation (aka H0)

Complete the five steps at https://cim.saddleback.edu/~class/cimRoot/de.html

Watch a prerecorded Canvas orientation webcast corresponding PDF viewgraphs, Webcasts are on Canvas under videos/Webcasts.

Checklist:

Hello.java

Watch one or two Canvas Web-Casts we have several previously recorded web-casts for Chapter 1
Read chapter 1 and take Canvas chapter 1 quiz.submit Filename: Hello.java; Help on using Submit - PermaLink,

The Hello.java assignment and most recent NetBeans/JDK install has been migrated to canvas discussion board.

Steps I took to install deprecated NetBeans 9.0, NetBeans 11.2 is easier:

  • Canvas has announcement on install the version 11.2 Netbeans,
  • Current NetBeans 9.0 doesn't include the JDK,
  • First, download and install the latest version of the latest Java SE Development Kit
  • Pay attention to install folder of JDK
  • Install NetBeans 9.0, its now under apache development., download Netbeans from the closest mirror site.
  • Try to start up the bin/netbeansX.exe, where X stands for the suffix most appropriate to your system
  • If NetBeans cannot find JDK, you need to set JDK path
  • Edit the etc/netbeans.conf, may need to copy it to a temporary file and then set the jdk_home path to the location of your JDK
  • copy your temporary file back in and set it as netbeans.conf

IntellJ Install Process

  • Download the Community Edition and then double click to install
  • Install IntellJ
  • Startup intellJ (most options are optional)
  • Click Create a new Project (if you have a working NetBeans, you can import NetBeans or just stay w NetBeans)
  • Inside of New Project Dialog Panel
    • Project SDK (if not install click download and install SDK)
    • Once Installed, click new button browse to the path of SDK
    • Location is like C:\Program Files\java\jdk-versionNumber, may also be D:\....
      For Mac its probably lib or bin
    • Select a Project name like cimp7a, then a location to store your files locally

Your textbook has video notes access on behind front cover, consider using this. We also have a revel online option to consider.

If you are familiar with Eclipse or intelliJ IDEA, you can use these instead. However, all web casts use NetBeans, all these ides are very similar. If you are currently using Sublime, text-pad and notepad++ you can add JDK to theses, but they are technically editors not a full feature IDEs.
Deprecated: Install Java JDK (Java Software Development Kit) and Text Pad - Help File

Watch the History of Java Video

For first assignment, write a Java class Hello, that outputs Hello World\n,
\n is the escape sequence for the newline character, you will be outputting "Hello World" new-line terminated (work through hints).

Review the Syllabus - this class grades has three parts: Canvas quizzes, Canvas tests & assignments.
You may also want to review the CIM site policy.

Sample Run (no input)

Hello World

NetBeans Output Window Sample Run 2 (no Input)

run:
Hello World
BUILD SUCCESSFUL (total time: 0 seconds)

Detailed Output:  "Hello Space World Newline"

Hints:

Determine the difference between: System.out.println( "Hello\n" ) versus System.out.print( "Hello\n"); versus System.out.println( "Hello" );

Consistency checks...

  • In Java class name and file name must always match, for this assignment class is Hello, file name is Hello.java.
  • The Output is almost always new line terminated, i.e., ends in a single new line (aka \n).

 

Exercise1_2.java (9th. 1.1 page 31; 10th 1.2 Page 30)


Watch Canvas Chapter 1 Web-casts Covering NetBeans
Submit Filename: Exercise1_2.java - Permalink,

Programming Exercise 1-2, page 30 (10th Edition Modified) (9th page 31) write Welcome to Java five (5) times. Each line is new line terminated. That implies each line ends with a new line. In Java and most modern day programming languages \n represent the escape sequence for a new line character, refer to hints in Hello.java for additional help.

Sample Run (no input):

Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java


NetBeans Output Window Sample Run 2 (no Input)
run:
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
Welcome to Java
BUILD SUCCESSFUL (total time: 0 seconds) Detailed Output: "Welcome Space to Space Java Newline" repeated 4 more times

Checklist:

TripleInteger.java

Submit Filename: TripleInteger.java Permalink,
and review documentation standard, all programs must be documented.

Write a program that reads an integer (integer value will be between -2^20 to 2^20) from standard input. Then outputs: "The number n tripled is n*3\n" where n is the integer just read. Output line is new-line terminated. You don't prompt the user for an integer.

Sample Run (input is 5, no prompt for input):

 5
The number 5 tripled is 15 Sample Run 2 (Input is -15): -15 The number -15 tripled is -45 NetBeans Output Windows, Sample Run 3 (input is 7) run: 7 The number 7 tripled is 21 BUILD SUCCESSFUL (total time: 3 seconds) Detailed Output: "The Space number Space # Space tripled Space is Space # Newline" where # is the default output for the number

Standard input, is used whenever an assignment must read data. Standard Input is the current input direction set by the System.in object. The default is usually keyboard but for submit its been redirected to read from a file. To read formatted data from Standard Input, create a Scanner object based on System.in object and then use the appropriate next method to read input. For example....

       //create a in Scanner object, based on the System.in Standard Input Stream 
		java.util.Scanner in = new java.util.Scanner( System.in );

        int n = in.nextInt( ); //read an integer from the scanner in stream
        //Note we are not prompting the user for the integer

Note Bene, almost all input data is free format, data is white space separated. It is very important to always get your sample runs, working in NetBeans before submitting, if not you will be wasting too much of your time with submit. Learn to follow I/O specifications this is the 21st century, all programming is based on sending data to another program based on an I/O specifications. You can be penalized by too many submit attempts.

Review required documentation standards, note the documentation standards solves this problem. However, you should solve the problem on your own from scratch. In Java practice makes perfect. You also need to memorize things System.in, Scanner, nextInt, etc.

P2.java

Submit Filename: P2.java, Permalink,
Review Canvas Chapter 1 Web-casts lists
Review Chapter 1, and if still available take Canvas chapter 1 quiz a second or third time.

Write a Java Program that reads in two integers firstNumber and secondNumber,
it should then print out...

firstNumber + secondNumber = Sum
firstNumber / secondNumber = DoublePrecisionDivision
firstNumber * secondNumber = Product

You have one space between all special characters (i.e., + / = and *).

If the first two numbers you will be reading in are 6 and 7, the output is...

      6 + 7 = 13
      6 / 7 = 0.8571428571428571
      6 * 7 = 42

You don't prompt the user for the two input values. Do not hard code the values for 6 and 7 in your program.

Sample Run 1 (Input is 6 and 7 ):

      6
      7       
      6 + 7 = 13
      6 / 7 = 0.8571428571428571
      6 * 7 = 42

NetBeans Sample Run 2 ( input 13 3 )

      run:
13 3
13 + 3 = 16
13 / 3 = 4.333333333333333
13 * 3 = 39
BUILD SUCCESSFUL (total time: 6 seconds)
Detailed Output: "# Space + Space # Space = Space # Newline" "# Space / Space # Space = Space #.#* Newline" "# Space * Space # Space = Space # Newline" where # is default output for an integer and #.#* is default output for a double.

Hints:

For standard output just use String concatenation, the first line is... System.out.println( firstNumber + " + " + secondNumber + " = " + sum );

In the above example firstNumber is converted to a String and then concatenated with the String " + " note " + " is the string space+space. In general...

  • when at least one operand is a String (e.g., number + String),
    the plus is overloaded to String concatenation
  • when operands are all numbers (e.g. number + number)
    the plus is treated like a standard arithmetic plus operator
  • try out System.out.println( firstNumber + "+" + secondNumber + (firstNumber+secondNumber) );
    remove the "+" string what takes place should make sense (all operands become numbers)
  • Try out these println, what are the results and why? System.out.println( (9/10) ); System.out.println( (double)(9/10) );
  • System.out.println( ( (double)9) / 10 ); /* on this fourth one its ambiguous 9 to double or result */ System.out.print( (double)9/10 );

  • Summary how does this work
    System.out.println(firstNumber + " + " + secondNumber + " = " + (firstNumber + secondNumber) );
    we work from innermost parathesis and out lets say firstNumber = 1; secondNumber =2
    so we have initially System.out.println(firstNumber + " + " + secondNumber + " = " + (firstNumber + secondNumber) );
    but when it solves (firstNumber + secondNumber) it only see integers so it does integer addititon so we get System.out.println(firstNumber + " + " + secondNumber + " = " + 3 );
    it then fills in firstNumber and secondNumber before the call so we get System.out.println( 1 + " + " + 2 + " = " + 3 );
    now when the java engine see 1 + " + " it has a number and string (mixed types) so it does "operator overloading" resulting in a string catenation so the call becomes System.out.println( "1 + 2 = 3" );

    this is a standard way we do calls to println
  • we could also to this
    String answer = firstNumber + " + " + secondNumber + " = " + (firstNumber+secondNumber);
    System.out.prinln( answer );

  • why we don't use these to the variables as a regular integer number?
    we could also add sum but its only used once so best just to calculate it with ()
    int sum = firstNumber + secondNumber;
    System.out.println(firstNumber + " + " + secondNumber + " = " + sum );

  • Can we write these lines without converting to string?
    we could use
    printf System.out.printf( "%d + %d = %d\n", firstNumber, SecondNumber, (firstNumber+secondNumber) );

  • in terms of best practices we would use:
    System.out.println(firstNumber + " + " + secondNumber + " = " + (firstNumber + secondNumber) );
    not want to create variables only used once not want to use printf unless we need special formatting, printf has higher overhead cost then just println

Checklist:

  • Make sure you have Completed Canvas chapter 1 quiz - click quiz grades tab to verify you current Canvas quiz grades..
  • Submit P2.java
  • On Canvas click quiz/test grades to verify you have take first two quizzes

May add team and/or individual programming contest)

details later on plan to add team and individual programming contest, will try to set start time that most can be on.

Exercise2_1.java Celsius to Fahrenheit (9th. 1.2 page 74; 10th. 2.1 page 69)

Canvas has several chapter 2 Web-casts watch one or two
Read Chapter 2.- chapter 2 Viewgraphs and take Canvas chapter 2 quiz.
Submit Filename: Exercise2_1.java (9th. Edition page 74; 10th Edition page 69) Permalink,

Programming exercises 2-1 (converting Celsius to Fahrenheit) and 2-6 summing digits in integer, page 62-62

Hints for Celsius to Fahrenheit:

  • Declare variables as double
  • output Strings are...
    "Enter a temperature in Celsius: "
    "The temperature is #,###.## in Fahrenheit.\n", where #,###.## outputs the number with commas every third digit left of decimal point and two digits right of decimal point.

May want to use this equation ( 9.0/5)*c + 32. Nota Bene different equations will yield slightly different results, but since we output only 2 digit precision, we should be okay.

Sample NetBeans Run (Input is 98, 100 and third time 45.5):

run:
Enter a temperature in Celsius: 98
The temperature is 208.40 in Fahrenheit.
BUILD SUCCESSFUL (total time: 11 seconds) run:
Enter a temperature in Celsius: 100
The temperature is 212.00 in Fahrenheit.
BUILD SUCCESSFUL (total time: 3 seconds). run:
Enter a temperature in Celsius: 45.5
The temperature is 113.90 in Fahrenheit.
BUILD SUCCESSFUL (total time: 3 seconds)

Output Details: Prompt "Enter Space a Space temperature Space in Space Celsius: Space"; Response is "The Space temperature Space is Space #,###.## Space in Space Fahrenheit Newline" where #,###.## is using the printf format string "%,.2f" . For most floating point output we will be using the conversion %,.2f. The % looks for an argument the comma adds a comma every three digits, the dot specifies the precision to the right of the decimal point, in this case two digits, the f stands for floating, look for a floating point number. Test the following examples using NetBeans...

Hints tests the examples below using NetBeans
System.out.printf( "format Specifier", arguments )
Java Statement Java Runtime Output Comments
System.out.printf( "Fahr is %,.2f\n", 23.4 ); Fahr is 23.40 % is the conversion specifier it matches the first argument 23.4, f means looks for a floating number (aka double)
System.out.printf( "Fahr is %,.2f\n", 1023.4 ); Fahr is 1,023.40 Comma is only added when need, we use comma, then precision dot 2
System.out.printf( "n=%.1f n*2=%.1f\n", 2.45, 2*2.45 ); n=2.5 n*2=4.9 .1 implies 1 digit precision to the right of decimal point
System.out.printf( "Cel=%,.2f\n", 2345.6778); Cel=2,345.68 Once again first % matches first argument, the comma adds a comma every 3 digits left of decimal point, dot 2 prints out 2 digits right of decimal point.
System.out.printf( "Low=%.2f\nHi=%.1f\n", 234.555, 400.62 ); Low=234.56
Hi=400.6
%.2f matches the first argument 234.555, and prints out two digits right of decimal point i.e., 234.56; the second %.1f matches the third argument and prints out 400.6
low = 20.554;
System.out.printf( "Low is %.2f okay\n",
low+7 );
Low is 27.55 okay the first % will match the first argument, the argument can be a literal, variable or even an equation. For %f the argument just needs to evaluate to a floating point value.
System.out.printf( "hello\nGood Bye\n" ); hello
Good Bye
% looks for an argument, all other characters just pass through, the escape sequence \n produces a new line.

Consistency Note

  • All prompts end in : space, no newline
  • When a prompt is present, sample run doesn't include the keywords input and output.
  • All class names begin with a capital letter
  • Last output line is always newline terminated (ends in \n ).
  • We never output a blank line. However, in the assignment display sample runs we have both before and after blank lines to increase readability.

Exercise2_6.java Sum Digits in Integer 10th Edition page 70

Canvas has several chapter 2 Web-casts watch one or two
Submit Filename: Exercise2_6.java See description at end PermaLink,
Review Chapter 2 Notes

Programming Exercise2_6.java, sum digits in an integer.

Your output is:

  • Enter an integer between 0 and 1000:
  • The sum of all digits in X is N

No new line after 1000: (its a prompt; you will be reading in an integer);
X is the number read N is the sum of the one to three digits.
Input data will not be negative or greater than or equal to 1000, it can be zero. For example input is 573; X is 573 and N is 15
using the inclusive definition of between based on MySQL, in standard english between is not inclusive.

For both assignments, you will be reading from standard input (aka System.in). When your program is run from the keyboard the standard input, is the keyboard. When it is batch, standard in is redirected to read from a file. Use Scanner to create the formatted standard input object. For example...

      java.util.Scanner in = new java.util.Scanner( System.in );
      ...prompt if in output...
      int x = in.nextInt( );

Sample Run (Input is 823):

Enter an integer between 0 and 1000: 823
The sum of all digits in 823 is 13 Sample Run 2 (Input is 15) Enter an integer between 0 and 1000: 15
The sum of all digits in 15 is 6 NetBeans Sample Run (Input is 999)
run:
Enter an integer between 0 and 1000: 999
The sum of all digits in 999 is 27
BUILD SUCCESSFUL (total time: 5 seconds)
Hint:

823/100 = 8; //this give you first digit; int sum = 8;
(823%100) = 23; //this gives a number representing the remaining two digits
Now 23/10 integer division gives us 2, sum +=2; 23%10 gives us the third digit which is 3. What is 8+2+3?

Detailed Output:

"Enter space an space integer space between space 0 space and space 1000: space"
"The space sum space of space all space digits space in space # space is space # Newline"
where # is the default output for an integer

Checklist

  • Take first attempt on Canvas chapter 2 quiz.
  • Submit Exercise2_1.java and Exercise2_6.java

CertificateDeposit.java (Similar to Exercise 2_21 10th Page 74)

Submit CertificateDeposit.java - compounded monthly -Permalink, - Canvas web-casts

All variables are double, given an initial investment of $1000.00 (one thousand dollars), write a program the first reads an annual interest rate, and then the number of months the Certificate of Deposit (CD) will be held. You first prompt user for interest rate, then term in months, You output the initial investment, annual rate, months and future value using a compounding monthly interest rate.

To complete this assignment refer to our documentation notes, which at the end includes a heavily commented CertificateDeposit program with most of the code removed. You should be able to write this program using just the comments. Note this program is over-commented, but for beginners it improves the learning process if you over comment than under comment.

Sample Run 1:

    Enter annual rate: 10
Enter CD term in months: 12
An initial investment of $1000.00 after 12 months at annual rate of 10.00% is $1104.71 Sample Run 2: Enter annual rate: 4.5
Enter CD term in months: 36
An initial investment of $1000.00 after 36 months at annual rate of 4.50% is $1144.25 Sample Run 3 (Input 1.25 and 72 - user enters 1.25 newline, then 72 followed by a newline): Enter annual rate: 1.25
Enter CD term in months: 72
An initial investment of $1000.00 after 72 months at annual rate of 1.25% is $1077.84 NetBeans Output Window Sample Run 4: (Input 0.25 and 60)
run:
Enter annual rate: 0.25
Enter CD term in months: 60
An initial investment of $1000.00 after 60 months at annual rate of 0.25% is $1012.58
BUILD SUCCESSFUL (total time: 21 seconds) NetBeans Output Window Sample Run 5 (Input 1.5 84)
run:
Enter annual rate: 1.5
Enter CD term in months: 84
An initial investment of $1000.00 after 84 months at annual rate of 1.50% is $1110.64
BUILD SUCCESSFUL (total time: 12 seconds)

Hints:

  • On the compound monthly equations make sure both term and rate are in months, a 10% rate annually is actually 10/(12*100). We divide the interest rate entered by 12 to go from annual to monthly. We then divide the monthly number by 100 to go from a whole number to an interest rate.
  • Compounding equation uses the power "^", the FutureValue = PV * ((1+MonthlyInterestRate)^NumberOfMonths); where one represent the current 100% value of PV.
  • For power Function, pause after your type Math. to see what Math. has available.
  • We are using the standard prompt (prompt colon space) "Enter annual rate: " prompt doesn't end in a new line.
  • Test this locally System.out.printf( "An initial investment of $%.2f at rate %.2f%%\n", 1000.0, 2.566 );
  • Use formatter for output, we want only two decimal point precision.
  • Output for the first part of the final output is System.out.printf( "An initial investment of $%.2f ", PV );

Distance.java

Canvas has several chapter 2 web-casts specifically 11/18/13 Fall 13.4 web-cast.
Review Chapter 2 Notes
Submit Distance.java, Permalink,

Write a program that prompts the user "Enter two points: ", a point is an x coordinate and a y coordinate, therefore two points is (x1, y1) and (x2, y2) which requires you to read four doubles. You will need to display the distance between the points with two digits pass the decimal point precision and comma every third digit to left of decimal point. To calculated the distance between to point use the distance formula:

distance = squareRoot( (x2-x1)^2 + (y2-y1)^2) );

where (x2-x1)2 is the square of the difference you can use either Math.pow( (x2-x1), 2.0 ) or (x2-x1)*(x2-x1)

distance = √ (x2-x1)2 + (y2-y1)2

where x1, y1 is the first point; x2, y2 is the second point.
Inside of Netbeans to access java.lang.Math API, type Math. pause or Math. and then Ctrl^space to get code completion options for square root, type sq in the dialog panel.

Sample Run (first point is 2, 2; second point is 5,2; x2=5 and y2=2)

Enter two points: 2 2 5 2
The distance between the two points is 3.00

Second Sample Run (first point x1=100.35; y1=200.0; second point 1000, 2500.34)

Enter two points: 100.35 200.0 1000.0 2500.34
The distance between the two points is 2,470.01

Third Sample Run

Enter two points: 0 0 1234567.89 1.0
The distance between the two points is 1,234,567.89

NetBeans Output Window Sample run (Input 2.4, 3.5,  -2.5, .5)

run:
Enter two points: 2.4 3.5 -2.5 .5
The distance between the two points is 5.75
BUILD SUCCESSFUL (total time: 13 seconds)

Hint:

  • Video on Java Distance program
  • Use formatter for output, we want only two decimal point precision and comma every third digit left of decimal point. Output code is...
  • System.out.printf( "The distance between the two points is %,.2f\n", ...
    Nota bene, printf uses formatter
  • Make your distance formula is a static method, so that it can be used to complete the next assignment.
  • Java distance discussion
Consistency Notes:
  1. Whenever we have a prompt it ends in colon space ': ', you have a space after the colon no space before colon.
  2. Whenever we have calculations that are mixed types (i.e., float, int and/or double), declarations and calculations will be of type double. Note in java.lang.Math almost all methods return and deal only with type double.
  3. All double output will use the format specifier .,2f, or $l,.02f for Currency. Note'...
    • , comma adds a comma every third digit
    • . dot represents precision, a %.2f means all output will have two digits right of decimal point

Checklist

  • Make sure you are aware of formatter, all floating point numbers will use the specification System.out.printf( "%,.2f", number);
  • Submit Distance.java

Exercise2_15.java (9th. Edition Page 78; 10th. Page 72)

Submit Exercise2_15.java, - (9th. Edition Page 78; in 10th. Exercise 2.19 page 73) - Permalink,
Watch Canvas Chapter 2 summary Web-casts

From Page 78 "( Geometry: area of a triangle) Write a program that prompts the user to enter three points ( x1, y1), ( x2, y2), ( x3, y3) of a triangle and displays its area. The formula for computing the area of a triangle is...

s = ( side1 + side2 + side3)/ 2;

Where side1 is length of side1; To determine length of each side you must use a distance formula. The Distance formula is...
side1 = squareRoot( (x2-x1)^2 + (y2-y1)^2) );

area = squareRoot{ s( s - side1)( s - side2)( s - side3) }

Sample Input is the six coordinates x1 y1 x2 y2 x3 y3
Sample Output is the prompt and calculation (all numbers and calculations are double precision)...

Enter three points for a triangle:
The area of the triangle is 33.60
Sample Run 1

Enter three points for a triangle: 1.5 -3.4 4.6 5 9.5 -3.4 
The area of the triangle is 33.60

Sample Run 2

Enter three points for a triangle: 2.5 -30.4 2.6 5 -9.5 -3.4
The area of the triangle is 213.75

Sample Run 3

Enter three points for a triangle: 0 0 0 1 1 1
The area of the triangle is 0.50 Sample Run 4
run:
Enter three points for a triangle: 23.4 34.2 -23.55 100.5 67.5 1000.0
The area of the triangle is 24,134.07
BUILD SUCCESSFUL (total time: 51 seconds) Sample Run 5 run: Enter three points for a triangle: 0 0 500 500 -1000 -2000 The area of the triangle is 250,000.00 BUILD SUCCESSFUL (total time: 18 seconds) Sample Run 6 run:
Enter three points for a triangle: 0 0 0 2 2 2
The area of the triangle is 2.00
BUILD SUCCESSFUL (total time: 17 seconds)

Hint:

For debugging, we often check each step one at time, so for the first test data try these steps

  1. use new Scanner( "1.5 -3.4 4.6 5 9.5 -3.4" ) as hard coded test data

  2. check the distance of each side, printf( "side1:%,.2f", side1 ); repeat for side2, and side3
    you should get: side1:8.95 side2:9.72 side3:8.00
  3. test the calculation of s which should be 13.34
  4. Finally your area is calculated
    The area of the triangle is 33.60

Use formatter for output, we want only two decimal point precision and comma every third digit left of the decimal point. Output code is...

System.out.printf( "The area of the triangle is %,.2f\n", ...

On input prompt do not have an enter, the final line should have an enter. Note side1 is length of side1, which starts at coordinate (X1, Y1) and ends at (X2, Y2). This is referred to as a distance formula. You may use this static method for computing distance...

public static double distance( double x1, double y1, double x2, double y2 ) 
	  { 
      	return Math.sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) );
      }
      
in main method:   
   side1 = distance( x1, y1, x2, y2 );
   side2 = distance( x2, y2, x3, y3 );
   side3 = distance( x3, y3, x1, y1 );

Checklist

  • Submit Distance.java first use this to derive your distance formula for Exercise2_15.java
  • Submit Filename: Exercise2_15.java (Ninth Edition Page 78)
  • Review Chapter 2 and take Chapter 2 Canvas Quiz another time
  • On Canvas click quiz grades, make sure all quizzes up to and including chapter 2 have been taken
  • Verify Submit, assignment grade table, it will appear right after you login and is on the on grading screen in the black grade tab.

Even.java

Submit Even.java, read in integer and output a line stating if it is even (true) or not (false). Permalink,
Try to complete program with Web-cast help, if you need help checkout Canvas Web-casts

Sample Run 1 (Input is 3):

Enter an integer: 3
Is 3 an even number? false

Sample Run 2:

Enter an integer: 16
Is 16 an even number? true

Sample Run 3:

run:
Enter an integer: 2224224
Is 2224224 an even number? true
BUILD SUCCESSFUL (total time: 9 seconds)

 

Hint
Prompt is: "Enter an integer: "
Output String is: "Is " + n + " an even number? " + boolean + "\n";

Consistency Notes Repeated...

  • Last output line is always newline terminated (ends in \n or uses println).
  • Note System.out.println( "\n" ); will produce two new lines
  • We never output a blank line. Sample Runs have pre and post blank lines to increase readability.

Checklist...

Exercise3_33M.java (9th. Edition Page 130 Modified; 10th Page 117)

Watch Canvas chapter 3 Web-cast
Read Chapter 3 and take Canvas chapter 3 quiz
Submit Filename: Exercise3_33M.java (9th. Edition Page 130 Modified; 10th Page 117) - PermaLink,

( Financial: compare costs) Suppose you shop for rice in two different packages. You would like to write a program to compare the cost. The program prompts the user to enter the weight and price of the each package and displays the one with the better price. If packages have the same price then output Packages have same price.

Here is a sample run (Input for first package is 25 weight and $11.99 price):

Enter weight and price for package 1: 25 11.99
Enter weight and price for package 2: 50 24.59
Package 1 has a better price.

Input will be the four values weight, price, for package 1; and weight price for package 2, read all data in as double.

Sample run 2:

Enter weight and price for package 1: 20.0 10.0
Enter weight and price for package 2: 10 5
Packages have the same price.

Sample run 3:

run:
Enter weight and price for package 1: 25 100
Enter weight and price for package 2: 25 50
Package 2 has a better price.
BUILD SUCCESSFUL (total time: 23 seconds

Output is the two prompts, and the package with the better price. Final line is newline terminated.

Hints

  • Make sure you understand the units in division, price/weight gives us cost per pound, weight/price gives us pounds per dollar. It is often best to put comments in English before you write the Java equation.

  • With cost/pound lower value is better, for example...
  • $20 buys 10lbs, we are spending $2/pound;
    $36 buys 12 lbs, we are spending $3/pound,
    lower value is better; $2 per pound is better than $3

  • With pound/dollar higher value is better, for example.
  • $20 buys 10lbs, 10/20 = 1/2 or 0.5lbs/dollar;
    $36 buys 12lbs, 0.333 lbs/dollar;
    higher value is better; 0.5lbs per dollar is better than 0.33 lbs/dollar.
  • So value sample run 3, we have value1=25lbs/$100 = .25lbs/dollar; and value2=25lbs/$50= .5lbs/dollar
    if( value1 > value2 ) //value 1has the better value
    but we have value2 > value1 so value2 has better value

Consistency Note

  • Whenever an assignment has been modified from the book it has an M prefix in the class name.
  • This assignment adds the situation when both packages have the same price.

Checklist

  • Submit Filename: Exercise3_33M.java (Ninth Edition Page 78 modified)
  • Review Chapter 3 and take Chapter 3 Canvas Quiz
  • Verify Submit, assignment grade table, it will appear right after you login and is on the on grading screen in the black grade tab.
  • Verify you have completed the first 4 quizzes, click on Canvas quiz grades tab.

HexagonArea.java

submit HexagonArea.java - PermaLink,


Exercise 4.4 page 151 10th Edition. "The area of a hexagon can be computed using the following formula (s is the length of a side):

Area = ( 6 * s2) / ( 4 * tan( π / 6 ) )

In general to find the area of a regular polygon on uses the equation:

Area = Number_of_Sides * (Length of each side)Squared/ ( 4 * tangent( π/ Number_of sides ) );

A Hexagon has 6 sides; In a regular polygon all sides are the same length. More details on hexagon area. Where π Math.PI is 180°.

Write a program that prompts the user to enter the side of a hexagon and display its area Here is a sample run:"

Sample Run 1: (user enters 5.5)

Enter the side: 5.5
The area of the hexagon is 78.59
NetBeans Sample Run 2: (user enters 2.345)
run:
Enter the side: 2.345
The area of the hexagon is 14.29
BUILD SUCCESSFUL (total time: 3 seconds)
NetBeans Sample Run 3: (user enters 2345.345)
 run:
Enter the side: 2345.345
The area of the hexagon is 14,291,090.16
BUILD SUCCESSFUL (total time: 6 seconds)

Consistency Notes - As usual

  • We are printing out the solution using "%,.2f"
  • All calculation are in double, its best to use Math.PI/6.0 rather than Math.PI/6
  • Prompt is "Enter the side: ", we have space after colon, no newline on this line.

SubString.java

submit SubString.java - PermaLink,

"4.22 (Check substring) Write a program that prompts the user to enter two strings and reports where the second string is a substring of the first string." 10th. Edition Exercise 4.22 Page 155.

Sample Run 1: (user enters ABCD then BC )

Enter string s1: ABCD
Enter string s2: BC
BC is a substring of ABCD

     Sample Run 2: (cat in_the_hat)
Enter string s1: cat Enter string s2: in_the_hat in_the_hat is not a substring of cat NetBeans Sample Run 3 run:
Enter string s1: ABcDeFg
Enter string s2: ABC
ABC is not a substring of ABcDeFg
BUILD SUCCESSFUL (total time: 9 seconds)

Hints

  • You will have to analyze java.lang.String, you only need to call one method.
  • You will be reading into two words one for s1, one for s2.

IntegerCount.java

submit IntegerCount.java - PermaLink,
Check Canvas chapter 3 and chapter 4 Web-casts

Read in integer numbers, one integer number per line, stop reading when you input 0, you will output the number integers read. You will first prompt the user with the string "Enter an integer, the input ends if it is 0: ".

Sample Run 1 (Input is 2 3 -100 1000 99 0):
     
Enter an integer, the input ends if it is 0: 2
3
-100
1000
99
0
The number of integers is 5
     
Sample Run 2 (Input is just 0):

Enter an integer, the input ends if it is 0: 0
No numbers were entered except 0

Sample Run 3 (Input is the string "2\n 3\n0\n-1\n23\n45.0\n23\n" - i.e., new Scanner( "5\n3\n0\n");
Enter an integer, the input ends if it is 0: The number of integers is 2   

Consistency Notes

  • Output lines are always newline terminated. The string for only 0 entered is "No numbers were entered except 0\n";
  • Unless noted otherwise, Input is always free form data Free form data is whitespace separated data. For Scanner newline terminated.
  • On CIM we always read from the stream System.in, so we always use Scanner in = new Scanner( System.in );
  • Scanner works on a Stream so the stream can be an actual String new Scanner( "5\n3\n0\n" );
  • On NetBeans System.in is directed to the keyboard, so you can paste data into the console run window.

Hints/Spoilers...

Analyze the code samples below, they are all reading integers until the user enters a 0. Why is the first version the cleanest?

Probably the cleanest solutions fewer lines of code and is readable.

this code is very readable, I would argue it is the most readable. Some would argue always avoid while( true ) and/or break. But in some cases a break is the cleanest solution. You have duplicate logic, if (n!=-1) to handle the body to avoid not true, and break you are adding extra variable,duplicate logic and extra code block which becomes error prone and less readability
3 Lines; 2 Variables 4 Lines; 2 Variables 6 Lines; 2 Variables 8 Lines; 3 Variables (Extra Variable)
int n;
while( (n=in.nextInt()) != 0 ) {
             ...
             }
while( true ) {
   int n = in.nextInt();
   if( n == 0 ) break;
   ...
   }
             
int n;
do {
    n = in.nextInt();
    if( n != 0 ) {
    ...
    }
} while( n != 0 );
boolean hasIntNotMinueOne = true;
while( hasIntNotMinusOne ) {
       int n = in.nextInt();
       if( n == 0 )
hasIntNotMinusOne = false; else { ... } }

Checklist

  • Submit Filename: Exercise3_33M.java (Ninth Edition Page 78 modified)
  • Review Chapter 4 and take Chapter 4 Canvas Quiz
  • Click the last tab on submit, to check to make sure all your submitted assignments have been recorded.
  • Take test 1 ( chapter 1-3 on Canvas)

Exercise4_1M.java (9th. Edition Page 167; 10th. Edition Page 192 5.1)

submit Exercise4_1M.java (9th Edition Page 167 modified; 10th Edition Page 192, Exercise 5.1 modified); - Permalink,

Watch a Canvas chapter 4 Web-cast.

Read in integer numbers, white space separated (free form data - a white space is either space, tab or newline just use nextInt() ), stop reading when you input 0, you will output the number of positive integers, negative integers, sum and floating-point average (type double - 2 digits after decimal point). You will first prompt the user with the string "Enter an integer, the input ends if it is 0: " From page 167..

"(Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number, using the standard "%,.2f" format specifier.
Sample run 1:

Enter an integer, the input ends if it is 0: 1
2
-1
9
0
The number of positives is 3 The number of negatives is 1 The total is 11 Average is 2.75 Sample Run 2: Enter an integer, the input ends if it is 0: 0 No numbers were entered except 0 Sample Run 3: using Input String "2\n-2\n4\n6\n6\n0\n3\n4\n5\n" in Scanner Enter an integer, the input ends if it is 0: The number of positives is 4
The number of negatives is 1
The total is 16
Average is 3.20

Hints:

  • use System.out.printf( "Average is %,.2f\n", average );
  • Since you are summing the integers total needs to be long (not int), you need to test all examples listed next.
  • Long uses 64bits, int is 32bits;
    • try out this program code...
      int big = 2000000000;
      /* note 2^32, uses first bit for sign (1 implies negative) 31 bits for the number
      2^31 = 2 * 2^30 = 2 * 10^9 = 2,000,000,000 (2^10 kilo 1000, 10^3) */
      int total = big * 2;
      System.out.println( big + " * 2 = " + total );
  • Operations will return type of largest operand, try these out.
    • int x = 2000000000;
      System.out.println( x*2 + " is also " + x*2L + " or not?" );
  • try these examples, Constants in java.lang.Integer representing MAX_INT
    • System.out.printf( "Integer Bits:%d MAX_INT:%,d 2^31=%,.2f\n", Integer.SIZE, Integer.MAX_INT, Math.pow( 2, 31 ) );
    • System.out.printf( " MAX_INT*2=%,d", Integer.MAX_INT*2 );
    • You can fix this, refer to the previous example on largest operand.
  • With division if all operands are integers, then result is an integer (need to typecast one operand to double)
    • try out this program code....
      double average = 9/10;
      System.out.println( "9/10 is " + average );

Checklist:

  • Make sure you have completed Canvas test 1.
  • Make sure you have taken chapter 4 quiz.(on Canvas click quiz grades to verify quiz and test grades)
  • Make sure you have completed all assignments up to and including Exercise4_1M.java. (submit lists table of assignment grades).

Pentagonal.java (Chapter 5.1M; 9th Page 213; 10th Page 234)

submit Pentagonal.java (9th Edition Page 213 5.1 modified; 10th edition Page 234 Exercise 6.1 modified) - Permalink,
Read chapter 5 and watch a Canvas chapter 5 Web-cast


Write Pentagonal.java from page 212 Ninth edition.

" 5.1M (Math: pentagonal numbers) A pentagonal number is defined as n(3n–1)/2 for n=1,2, . . ., and so on.
Therefore, the first few numbers are 1, 5, 12, 22, . . ..
Write a method with the following header that returns a pentagonal number:
public static int getPentagonalNumber(int n)"
Pentagonal numbers illustration and general equation....

Which is Pn = ( 3 * n2 - n )/2

Note for n =1 we have one vertex point
for n = 2 we share vertex points for n=1 and add four more points this gives a pentagonal P2= 5 points

For P3, we share vertex points of P2 and add 7 more points this gives P3 = 12 points

For P4 we add 10 more points + 12 from P3 gives a P4 = 22.

You will read a single integer from standard input and print out the the first n pentagonal numbers, where n was integer just read. All numbers will be printed space then number, last pentagonal number is new line terminated.

Sample Run 1 (Input 2):

Enter an integer: 2
The pentagonal numbers are: 1 5

Sample Run 2 (User input's 4):
Enter an integer: 4 The pentagonal numbers are: 1 5 12 22 Sample Run 3 (NetBeans output window user inputs 7) run:
Enter an integer: 7
The pentagonal numbers are: 1 5 12 22 35 51 70
BUILD SUCCESSFUL (total time: 7 seconds)

Hint the method getPentagonalNumber( int n ), is singular, but you can write your method to kick out and array 1..n.

Hint,

  • For Pentagonal.java with input 2, you will need to output:space1space5newline, so we print a space then a number.
  • The only catch is the last number ends in a newline..
  • Lets look at another example, you want to read in n and print out the squares of 1 up to n^2, last one is newline terminated.
    For example, input n=3; Output: "The square numbers are: 1 4 9\n" - this Simple loop will work:

    System.out.print( "The square numbers are: " );
    for( int i = 1; i <= n ; ++i ) System.out.print( i*i + ( i == n ? "\n" : " " ) );

    But this might be easier to read (we print space number, newline after loop)
    System.out.print( "The square numbers are:" ); //no space
    for( int i=1; i <= n; ++i ) System.out.print( " " + i*i );
    System.out.println();


ReverseNumber.java (Chapter 5.3M)

submit Filename: ReverseNumber.java ( 8th Edition 5.3M & 9th Edition 5.4M; 10th Edition page 234 Exercise 6.4 Modified); - PermaLink,
watch a Canvas Chapter 5 Web-cast

Input a positive integer,multiply the input integer by two, then call the method...

public static long reverse( long i ) // The method long reverse( long i) returns the integer in reverse order.

Sample Run 1 (Input 12):

Enter a positive integer: 12
12 doubled is 24 and then reversed is 42

Sample Run 2:

Enter a positive integer: 540
540 doubled is 1,080 and then reversed is 801

Sample Run 3:

Enter a positive integer: 1204500
1,204,500 doubled is 2,409,000 and then reversed is 9,042

Consistency notes repeated.

  • Prompt is "Enter a positive integer: " no newline at end.
  • Single output line is newline terminated we are using , format specifier with decimal integers.

Hints:

System.out.printf( "%,d doubled is %,d and then reversed is %,d\n", n, ... );
Refer to hints in Exercise4_1M.java for handling large numbers (you need to type small programs that illustrate these hints)

For large numbers refer to hints on Exercise4_1M.java.

Checklist...

  • Complete Canvas chapter 5 quiz
  • Click quiz grades to verify quiz and test 1 grades.
  • Make sure you have submitted both Pentagonal.java and ReverseNumber.java

.

Extra Credit Mean.java (9th 6.11 page 247)

Chapter 7 Arrays Assignments and Quizzes is Extra Credit Fall 2016

Submit Filename: Mean.java - (9th Edition p 247; 10th Edition p 278 Exercise 7.11) - Permalink,
Watch a Canvas chapter 6 Web-cast

Programming Exercise 6-11M page 223 (9th Edition 6.11 page 257) computing deviation, hints....

  • test your program using the book's sample array data,
  • but for submit read in 10 doubles
  • declare all variables as double

Sample Input 1: 1.0 3.0 5.5 7.6 22.0 10.0 7.0 8.0 9.0 3.23
Output (No input prompt)...

The mean is 7.63
The standard deviation is 5.81

Sample Input 2: 23.0 45.5 34.6   45.7  56.7
89.0 78.0 89.654 78.34 100.34
Output...
The mean is 64.08
The standard deviation is 26.42

For standard deviation use the corrected sample standard deviation
- std = √ { 1/(N-1 ) ∑ (xi - xavg)2 }

Hints:

  • Will be using the standard output format System.
  • System.out.printf( "The mean is %,.2f\n" + mean(x) );
  • System.out.printf("The standard deviation is %,.2f\n", deviation(x) );

Checklist:

  • Complete Canvas test 2 chapters 3-5
  • On Canvas verify all quiz/test grades using the quiz/grades tab.
  • On submit verify all assignment grades.

 

Extra Credit SelectionSort.java revised Descending Order

Submit Filename: SelectionSort.java (9th Edition page 259 6.20; 10th Edition Page 280 7.20) - Permalink,
Watch a Canvas chapter 6 Web-cast

You first read in an integer representing the size of the double array (e.g., n=3), you then read in n doubles (e.g., -23.45 587.5 45.0). You output the descending sorted array each value has a space separator, except the last number which will be newline terminated. You are using selectionSort to sort the array.

Sample Video on Select Sort - 15 Sorts in 6 Minutes (Selection is first)

Sample Input 1: 15 1.0 3.0 5.5 7.6 22.0 13.0 7.0 8.0 9.0 3.23 32.0 9.0 19.0 8.0 7.6
Output (no input prompt): 32.0 22.0 19.0 13.0 9.0 9.0 8.0 8.0 7.6 7.6 7.0 5.5 3.23 3.0 1.0

Sample Input 2: 3 -23.45 587.5 45.0
Output: 587.50 45.0 -23.45
Note Output String is "587.50 45.0 -23.45\n"

Hints:

  • test your program by hard coding an array of doubles, (e.g., double[] list = { -23.45, 587.5, 45.0 }; )
  • for submit you will first read in the size of the array, and then the number of doubles all from standard input (System.in)
  • Declare all variables as double, output all numbers using just System.out.print not System.out.println.
  • You will output the numbers sorted in descending order space delimited, with last number ending with only a newline.
    All numbers will end with a space, except for the last one which ends with a newline.

Spoilers

  • Declare input array with no size (set size after reading in size). double[] list;
  • Create a Scanner( System.in ) object, then read in the array size, (int size = in.nextInt());
  • Use the array size to set the size of your list list = new double[ size ];
  • Then read in doubles using nextDouble(), do this from i=0; i<size
    for( i=0; i < list.length ; ++i ) list[ i ] = input.nextDouble( );

Checklist