Insert before line 241 "System.out.print("Secret Message: ");"
Insert between curly braces lines 247 and 248 "System.out.print((char)result[b]);"
Run the main() -
When you run it the first time, select Steganography_Controller.java" as the main()
Save and Test
Notes -
Works best if you copy an image into the project root folder
Encode a simple message
Program creates a file with the message as the filename
Decode the message to the command prompt
Have Fun!
Advanced -
Review the code to see how it works
43) Thursday, 06/14/18 - Java Two Pages, SQL Logon 42) Wednesday, 06/13/18 - AT&T Guest Speaker 41) Tuesday, 06/12/18 - Mr. Clarke Out Sick - Java Two Pages, SQL Logon
Task - MultiPages - Practice moving between Java JFrame Forms -
to create the "cmdPage2ActionPerformed" event
-
Page2 p2 = new Page2(); // create a link to page 2
p2.setVisible(true); // set page 2 visible true
setVisible(false); // set current page visible false
to create the "cmdPage1ActionPerformed" event
-
Page1 p1 = new Page1(); // create a link back to page 1
p1.setVisible(true); // set page 1 visible true
setVisible(false); // set current page visible false
Task - Login to Logon - Add a logon process to the Logon project -
-
try {
// get user input from the two new text fields
String id = txtID.getText();
String pw = txtPW.getText();
// build sql statement
sql = "SELECT * FROM users ";
sql += "WHERE userid = '" + id + "' AND password = '" + pw + "';";
System.out.println(sql);
stmt = conn.createStatement();
// execute SQL statement
ResultSet rs = stmt.executeQuery(sql);
// count how many rows in the result set
rs.last();
int count = rs.getRow();
rs.first();
// display results if one row
if(count == 1) {
id = rs.getString("userid");
pw = rs.getString("password");
JOptionPane.showMessageDialog(null, "Welcome " + id);
} else {
JOptionPane.showMessageDialog(null, "User ID or Password Not Found!");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
40) Monday, 06/11/18 - Java and MySQL Logon
Project - Logon -
Concept -
Create a Java project to read/write a MySQL database
Prepare -
Create a [F]ile [N]ew Java Application project named Logon
Be sure to name the project before you save it
Save to your Z:/java folder
Add new JFrameForm LogonGUI
Design -
Add a large textarea to display userids and passwords from a database table
Add command buttons for [Show] and [Exit]
Task -
-
Column/Field
Data Type
Other
account
integer
auto-increment, primary-key, unique
userid
String
password
String
lastdate
Date
-
account userid password lastdate
1 adam adam1 2018-06-04
2 beth beth2 2018-06-04
3 chad chad3 2018-06-04
4 dana dana4 2018-06-04
5 evan evan5 2018-06-04
6 fran fran6 2018-06-04
7 gary gary7 2018-06-04
8 hana hana8 2018-06-04
9 ivan ivan9 2018-06-04
10 june june10 2018-06-04
A prime number is a whole number greater than 1 whose only factors are 1 and the number itself
1 is not considered prime
A natural number greater than 1
Cannot be formed by multiplying two smaller natural numbers
Example, 5 is prime because the only ways of writing it as a product (1 × 5) involves 1 and 5 itself
6 is not prime because it is the product of two numbers (2 × 3) that are both larger than 1 and smaller than 6
A simple but slow method of checking the primality of a given number is called trial division
Test whether n is a multiple of any integer between 2 and √n
There are infinitely many primes, as demonstrated by Euclid around 300 BC
As of January 2018, the largest known prime number has 23,249,425 decimal digits
Primes are used in information technology, such as public-key cryptography
First few primes -
2 - only 1 * 2 - Prime
3 - only 1 * 3 - Prime
4 - 1*4 and 2*2 - Not Prime
5 - only 1 * 5 - Prime
6 - 1*6 and 2*3 - Not Prime
7 - only 1 * 7 - Prime
8 - 1*8 and 2*4 - Not Prime
9 - 1*9 and 3*3 - Not Prime
Prepare -
Create a [F]ile [N]ew Java Application project named Prime
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Command line or visual JFrame Form
Include pseudocode as comments in your project
Part 1 - Display all prime numbers between 2 and 1000
Part 2 - Get a user-entered number and display if it is prime or not prime
Advanced -
If you did command line, now to visual
If you did visual, now do command line
31) Tuesday, 05/29/18 - Armstrong Numbers
Project - ArmstrongNumbers -
Concept -
An Armstrong number of three digits is an integer
The sum of the cubes of its digits is equal to the number itself
Example -
153 is an Armstrong number since 1**3 + 5**3 + 3**3 = 153
153 // original number
1**3 = 1 // cube of first digit
5**3 = 125 // cube of middle digit
3**3 = 27 // cube of last digit
// first cube plus middle cube plus last cube
1 + 125 + 9 = 153 // calculated number
// original number equals calculated number
153 == 153 // returns true
153 is an Armstrong number = true
Write a program to find all Armstrong numbers in the range of 100 to 999
Prepare -
Create a [F]ile [N]ew Java Application project named ArmstrongNumbers
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Pseudocode the problem
Code the solution
Advanced -
Create a visual Java JFrame Form to do the same
Monday, 05/28/18 - Memorial Day - School Closed
In Flander's Field
By Lt. Col. John McCrae, 1915
In Flanders fields the poppies blow
Between the crosses, row on row
That mark our place; and in the sky
The larks, still bravely singing, fly
Scarce heard amid the guns below
We are the dead. Short days ago
We lived, felt dawn, saw sunset glow
Loved, and were loved, and now we lie
In Flanders fields
Take up our quarrel with the foe
To you from failing hands we throw
The torch; be yours to hold it high
If ye break faith with us who die
We shall not sleep, though poppies grow
In Flanders fields
Oh! You who sleep in Flanders fields
Sleep sweet – to rise anew!
We caught the torch you threw
And holding high, we keep the faith
With all who died
We cherish, too, the poppy red
That grows on fields where valor led
It seems to signal to the skies
That blood of heroes never dies
But lends a lustre to the red
Of the flower that blooms above the dead
In Flanders field
And now the torch and poppy red
We wear in honor of our dead
Fear not that ye have died for naught
We'll teach the lesson that you wrought
In Flanders field
There are a total of ( n ( n + 1 ) ) / 2 integers in n rows
Example - ( 5 ( 5 + 1 ) ) / 2 integers in 5 rows -
( 5 ( 5 + 1 ) ) / 2
( 5 ( 6 ) ) / 2
( 30 ) / 2
15
A simple pattern to print but helpful in learning how to create other more complex patterns
The iey to developing the pattern is to use nested loops and methods like System.out.print() and println()
A good programmer will be able to look a pattern and break it into nested loops
Formal definition of Floyd's Triangle ~ "A right angled triangle of array of natural numbers named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, stating with 1 in the top left corner."
Example -
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task -
Design a solution to print this table using nested loops
28) Wednesday, 05/23/18 - Remove Duplicates from an Array
Project - RemoveDuplicates -
Concept - Java technical interview question -
Remove duplicates from an integer array without using any collection API classes -
Array of positive integer numbers - no negative, no zero values
If you need to do this for any project work, use Set interface, particularly LinkedHashSet, because that keeps the order on which elements are inserted into Set
For technical interview perspective, do this using either loops or recursion
A naive (simple) solution has lots of limitation to be considered
Not the best solution but still a solution
Main problem is not finding duplicates but removing them
An array is a static, fixed length data structure
You can not change its length
Deleting an element from an array requires creating a new array and copying content into that array
If your input array contains lots of duplicates this results in lots of temporary arrays
It also increases cost of copying contents, which can be very bad
Given this restriction, you need to come out with a strategy to minimize both memory and CPU requirements
// create a method "remover()"// one parameter Array of int[] "a"// sort the array// display array "a"// create a new array int[] "b" of the same length// set the first value in "b" to the same value in "a"// loop from 1 to length of "a"// if "a[i - 1" is the same as "a[i]"// set "b[i]" the same as "a[i]"// end if// end loop// display array "b"// end function
Advanced -
Create an Array of 50 random integer numbers between 1 and 20
Remove duplicates
27) Tuesday, 05/22/18 - Solve the First Recurring Problem using a Hash Table
From Friday, 05/18/18
26) Monday, 05/21/18 - Google Interview Question - How to Solve the First Recurring Problem
Project - FirstRecurring -
Concept -
Given a String of letters of unknown length, find and return the first character that repeats
For example - DBCABA should return "B"
View the video - youTube.com - Google Coding Interview Question and Answer - First Recurring Character
Use the pseudocode at minute 6:00
Prepare -
Create a [F]ile [N]ew Java Application project named FirstRecurring
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Pseudocode -
def first_recurring(given_string):
counts = {} // dictionary or hash table // we used an Array of char
for char in given_string:
if char in counts:
return char
counts[char] = 1
return None
Solution -
package firstrecurring;
import java.util.HashSet;
public class FirstRecurring {
// Global variables
static int count = 0; // count how many times each process runs
public static void main(String[] args) {
String s = getString();
//s = "Georgetown University";
//s = "DBCABA";
s = "abcba";
s = s.toUpperCase();
System.out.println("Original String: " + s);
System.out.println("First Recurring using Loops: " + getLoop(s) + ", count: " + count);
System.out.println("First Recurring using Array: " + getArray(s) + ", count: " + count);
System.out.println("First Recurring using Hash: " + getHash(s) + ", count: " + count);
} // end of main
public static String getString() {
// return a random number of random uppercase letters
String s = "";
int r;
int hm = (int) Math.floor(Math.random() * 20) + 6;
for (int i = 0; i < hm; i++) {
r = (int) Math.floor(Math.random() * 26) + 65;
s += (char) r;
}
return s;
}
public static char getLoop(String s) {
// using nested loops// this solution DOES NOT WORK with input string "ABCBA"
count = 0;
for(int i = 0; i < s.length() - 1; i++) {
for(int j = i + 1; j < s.length(); j++) {
count++;
if(s.charAt(i) == s.charAt(j)) {
return s.charAt(i);
}
}
}
return '0';
}
public static char getArray(String s) {
// using arrays
count = 0;
char[] cA = new char[26];
for (int i = 0; i < cA.length; i++) {
cA[i] = '.';
}
char[] chars = s.toCharArray();
for (char ch : chars) {
for (int i = 0; i < cA.length; i++) {
count++;
if (ch == cA[i]) {
return ch;
} else if (cA[i] == '.') {
cA[i] = ch;
i = 1000;
}
}
}
return '0';
}
public static char getHash(String s) {
// using a hash tablegeeksForGeeks.org - HashMap
count = 0;
char[] chars = s.toCharArray();
char c;
HashSet h = new HashSet<>();
for(int i = 0; i < chars.length; i++) {
count++;
c = chars[i];
if(h.contains(c)) {
return c;
} else {
h.add(c);
}
}
return '0';
}
} // end of class
Advanced -
25) Friday, 05/18/18 - Visual Java Tip Calculator
Project - tipCalculator -
Concept -
Use pseudocode to design the project
Typical Tip Values - Total price of bill times a certain percentage based on quality of service
Examples -
Quality of Service
Tip Percentage
Bill
Tip Amount
Superior
20 %
$100.00
$20.00
Average
15 %
$100.00
$15.00
Substandard
10 %
$100.00
$10.00
Prepare -
Create a [F]ile [N]ew Java Application project named tipCalculator
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Design a Visual Java form similar to the one shown
Choose valid form objects and object names -
// txtAmount (Text Field)// grpQuality (Button Group, not visible, use navigator panel to rename)// optOutstanding (Radio Button, set button group property to grpQuality)// optExcellent (Radio Button, set button group property to grpQuality)// optOkay (Radio Button, set button group property to grpQuality)// cmdCalc (Button)// txtTip (Text Field, uncheck the editable property)// txtTotal (Text Field, uncheck the editable property)// cmdExit (Button)
Double-Click to create the cmdExitActionPerformed event -
// Program and test the exit button
int yesNo = JOptionPane.YES_NO_OPTION;
int exitAnswer = JOptionPane.showConfirmDialog(null, "Really Exit?", "Exit Message", yesNo);
if(exitAnswer == 0) {
System.exit(0);
}
Program the tip button - (This is like pseudocode) -
// Prepare the output string
DecimalFormat df = new DecimalFormat("$.00");
// Question - How do you import the DecimalFormat?// Parse the String amount into a double variable
double dblAmount = Double.parseDouble(txtAmount.getText());
// Set a default percent amount
double dblPercent = .15;
// Determine the percent amount by finding out which radio button isSelected
if(optOutstanding.isSelected() == true) { dblPercent = .20; }
if(optExcellent.isSelected() == true) { dblPercent = .15; }
if(optOkay.isSelected() == true) { dblPercent = .10; }
// Question - How can you make the code above more efficient?// Multiply the amount by the percentage giving the tip
double dblTip = dblAmount * dblPercent;
// Add the tip to the amount giving the total
double dblTotal = dblAmount + dblTip;
// Display the tip and total as String formatted for two decimal points
txtTip.setText(df.format(dblTip));
txtTotal.setText(df.format(dblTotal));
// Test all possible tip percentages
Advanced -
Add a magnificient tip percentage of 25% -
Bill Amount
Quality of Service
Go Button
Tip and Total
Tip:
Total:
Add a way for the user to enter a percentage amount
Add a feature to divide the total among a group of people -
There are a total of ( n ( n + 1 ) ) / 2 integers in n rows
Example - ( 5 ( 5 + 1 ) ) / 2 integers in 5 rows -
( 5 ( 5 + 1 ) ) / 2
( 5 ( 6 ) ) / 2
( 30 ) / 2
15
A simple pattern to print but helpful in learning how to create other more complex patterns
The iey to developing the pattern is to use nested loops and methods like System.out.print() and println()
A good programmer will be able to look a pattern and break it into nested loops
Formal definition of Floyd's Triangle ~ "A right angled triangle of array of natural numbers named after Robert Floyd. It is defined by filling the rows of the triangle with consecutive numbers, stating with 1 in the top left corner."
Example -
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Task -
Design a solution to print this table using nested loops
The main point is to build the logic
This will help you a lot in the long run
Hints -
Don't write a program
Just write the pseudocode
Use Microsoft Word or Google Docs or even notepad
Save to your "Z:/DoNow/" folder or Google Classroom titled "Floyd's Triangle.doc"
23) Wednesday, 05/16/18 - Roman Numerals 22) Tuesday, 05/15/18 - Roman Numerals
Project - RomanNumbers -
Concept -
Convert between Roman numerals and Integer numbers
The Integer year 2018 can be written as "MMXVIII" in Roman numerals
The Roman numerals "MCMLIV" converts to the Integer year 1954
Prepare -
Create a [F]ile [N]ew Java Application project named RomanNumbers
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Tuesday - Convert a given Integer number to an equivalent Roman numeral -
For example, if given integer is 5 then your program should print "V"
Input will be within the range from 1 to 2020
Return the Roman numeral as all uppercase, 10 should return "X" not "x"
Wednesday - Convert a given Roman numeral to an equivalent Integer number -
Reverse of above
For example, if given String is "X" then your program should print 10
Input will be within the range from "I" to "MMXX"
Convert all input to uppercase, input of "x" or "X" should return 10
Advanced -
Are there different ways to accomplish this?
21) Monday, 05/14/18 - Regular Expressions and Pattern Matching
Project - Regex -
Concept -
Practice using regular expressions and pattern matching
Prepare -
Create a [F]ile [N]ew Java Application project named Regex
Be sure to name the project before you save it
Save to your Z:/java folder
Task - Build regex to match these patterns -
A phone number - "(732) 264-5043"
A social security number - "111-22-3333"
An email address - "m.clarke@mail.ocvts.org"
A date - "05/14/18" or "05/14/2018" or "5/14/18" or "5/14/2018"
Advanced -
What other pattern matching can you think of and implement?
Right-click and create a New, JFrame Form named "GUI.java" file
Right-click and safely delete and refractor the "Logon.java" file
Run the program once to select "GUI.java" as the main
Design a form similar to shown -
Label objects as needed to identify and inform
Text field named "txtUserID", add "static" to the property code variable modifiers
Password field named "txtPassword", add "static" to the property code variable modifiers
Buttons named "cmdClear", "cmdLogon", and "cmdExit"
Text area named "txtMessage", add "static" to the property code variable modifiers
Save and Test
Double-click and code the "cmdExit" button -
System.exit(0); // exit with zero errors
Save and Test
Double-click and code the "cmdClear" button -
txtUserID.setText(""); // clear the userid field
txtPassword.setText(""); // clear the password field
txtUserID.requestFocus(); // set the cursor focus
txtPassword.setText(""); // clear the password field when focused
Save and Test
Add global variables AFTER the "public class GUI" -
private static String s = "", id = "", pw = ""; // string, id, password
private static int t = 0, i = 0, total = 0; // tilde, index, total users
private static String[][] users = new String[99][2]; // up to 99 users t2o-dimension array
private static boolean found = false; // check if id and password match
Save and Test
Add code AFTER the "public GUI() { initComponents();" -
// try {// declare a new filereader "fr" for "users.txt"// declare a new bufferedreader "br" for "fr"// set total to 0// while readline "br" into "s" not equal null// set "t" to the indexof "~" in "s"// set the users first element to the value of "s" before "t"// set the users second element to the value of "s" after "t"// increment "total"// end while// { testing } set "s" to ""// { testing } for each user// { testing } add element 0 and element 1 and newline to s// { testing } end for// { testing } display "s" to "txtMessage"// { testing } remove after it works// catch and display any exception
Save and Test
Double-click and code the "cmdLogon" button -
// set "found" to false// set "i" to 0// set "id" by gettext from "txtUserID"// create a new char array "cArray"// set "cArray" by getpassword from "txtPassword"// set "pw" to new String(cArray)// while "i" is less than "total" and found is false// if the first element of users equals ignore case "id" and// the second element of users equals ignore case "pw"// set found to true// end if// increment "i"// end while// if found is true// decrement "i" because we added one too many// settext "txtMessage" to "User " user[i][0] " successfully logged on"// else// settext "txtMessage" to "Incorrect UserID or Password"// end if
Save and Test -
// test with a valid userid and password// test with another valid userid and password// test with a valid userid and but an invalid password// test with another valid userid and but an invalid password// test with an invalid userid and an invalid password// test with another invalid userid and an invalid password// test with an invalid userid but a valid password// test with another invalid userid but a valid password
Advanced -
Add colors
Add an image
17) Tuesday, 05/08/18 - Palette Practice 16) Monday, 05/07/18 - Palette Practice
Practice -
Open PalettePractice
Add a button group object
In the Navigator panel change the name to "grpGender"
Add two radio button objects, edit text to "Male" and "Female"
Change the property "ButtonGroup" to "grpGender"
Test that only one button can be selected
Add another button group object
In the Navigator change the name to "grpMail"
Add two more radio buttons, edit text to "Yes" and "No"
Change the property "ButtonGroup" to "grpMail"
Test that yes/no works and does not conflict with male/female
Add a check box object named "chkRemember"
Edit text to "Remember?"
Double click to create the action performed event
Write code to test if chkRemember isSelected
if true setText in txtName to "Thank you"
if false setText in txtName to "Are you sure?"
15) Friday, 05/04/18 - Mr. Clarke Out Sick - Integrating Excel into Word into PowerPoint
Embed an Excel spreadsheet chart into a Word document and the Word document into a PowerPoint presentation
Create a new spreadsheet named "CustomerRatings.xlsx" save to your DoNow folder
Fill in data scale of 0 to 10 -
A B
1 Name: Rating:
2 Adam 8.5
3 Beth 7
4 Chad 9
5 Dana 7.5
Highlight the rows/columns and insert a bar chart
Save
Word -
Create a new document named "CustomerRatings.docx" save to your DoNow folder
Add text, something like -
On Friday, May 4th, 2018, we surveyed four customers.
Presented here is the result of the survey:
< insert Excel chart here >
Please comment on our website: www.overTheRainbow.edu
Embed the Excel chart into the Word document
Save
PowerPoint -
Create a new presentation named "CustomerRatings.pptx" save to your DoNow folder
Title slide -
Title "Survey Results"
Subtitle < your name >
Slide 1 -
Title: "Introduction"
Text: "Customer survey conducted May 4th, 2018"
Slide 2 -
Title: "Results"
Text: < insert Word document >
Slide 3 -
Title: "Conclusion"
Text: "Needs work"
Embed Word document into the PowerPoint presentation
Save
Modify -
Add four (4) more names and ratings to the spreadsheet
Re-embed into the document
Add a paragraph to the document -
We are generally happy with the results of our survey.
Re-embed into the presentation
Experiment with designs for the presentation
This should take you the entire 2-hour class period
' VB.NET pseudocode' onChange any quantity' multiply the quantity by the price for that book' set the total for that book' recalculate a subtotal' recalculate and display tax' recalculate and display total' onClick print' build an output string with name, address, total number of books, tax, and total' display results in the output textarea' onClick clear' clear all fields and set all quantities to zero
A fundamental relation in Euclidean geometry among the three sides of a right triangle
The square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides
Can be written as an equation relating the lengths of the sides a, b and c, often called the "Pythagorean equation" -
a2 + b2 = c2
where c represents the length of the hypotenuse and a and b the lengths of the triangle's other two sides
Test data -
32 + 42 = 529 + 16 = 25
What other tests can you run?
Prepare -
Create a [F]ile [N]ew Java Application project named RightTriangleChecker
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Read three (3) integer numbers and determine if they can form a right triangle
Advanced -
"3, 4, 5" do indeed form a right triangle because 32 + 42 equals 52
Suppose the user enters "4, 5, 3" where 42 + 52 does not equal 32
Fix it so it works regardless of the order of the numbers entered
43) Friday, 04/13/18 - Java Person Class for a PhonebookMarking Period 3 42) Thursday, 04/12/18 - Java Person Class for a Phonebook 41) Wednesday, 04/11/18 - Java Person Class for a Phonebook 40) Tuesday, 04/10/18 - Java Person Class for a Phonebook 39) Monday, 04/09/18 - Java Person Class for a Phonebook
Project - Phonebook -
Concept -
Create a Java project to keep track of all your friends' names, phones, and emails
Save (read and write) data to a text file contacts.txt
Two files - Phonebook.java Class with main() and Person.java Class with information about a person
What do we need to keep track of in Person.java Class? Data types? Variable names? -
What processes (methods) will Person.java Class contain? -
What do we need to keep track of in Phonebook.java Class main()? Data types? Variable names? -
What processes (methods) will Phonebook.java Class main() contain? -
Prepare -
Create a [F]ile [N]ew Java Application project named Phonebook
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
wikipedia.org - Unified Modeling Language (UML) diagram for Person Class -
Class: Person
State (property variables):
- int indexNumber
- String firstName
- String lastName
- String phoneNumber
- String eMail
Behavior (method functions):
+ Person() (constructor)
+ Person(int n, String f, String l, String p, String m) (constructor)
+ setPhone(String: p)
+ setEmail(String: m)
+ showPerson(int: i)
Person.java class -
// Copy and paste into the Person class// global instance variables
int number;
String name, phone, email;
// default constructor
Person() {}
// detailed constructor
Person(int n, String a, String p, String m) {
number = n;
name = a;
phone = p;
email = m;
}
// mutator methods
public void setNumber(int n) {
number = n;
}
public int getNumber() {
return number;
}
public void setName(String a) {
name = a;
}
public String getName() {
return name;
}
public void setPhone(String p) {
phone = p;
}
public String getPhone() {
return phone;
}
public void setEmail(String m) {
email = m;
}
public String getEmail() {
return email;
}
// return all values in one class object instance
public String display() {
String str = name + " " + phone + " " + email;
return str;
}
PhoneBook.java class -
// Copy and paste after package phonebook; before public class PhoneBook// imports
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
PhoneBook.java class -
// Copy and paste into the PhoneBook class above the main()// global variables
static Scanner stdIn = new Scanner(System.in);
static File fileName = new File("contacts.txt");
static Person[] contact = new Person[0];
static Person[] temp = new Person[contact.length + 1];
static String str = "", name = "", phone = "", email = "", again = "Q";
static int i = 0, tilde = 0, x = 0;
PhoneBook.java class -
// Copy and paste into the PhoneBook class above the main()// A method to display all values in all persons
public static void list(Person[] c) {
for(int i = 0; i < c.length; i++) {
if(c[i] != null) {
System.out.println(i + ": " + c[i].display());
}
}
}
PhoneBook.java class -
// Copy and paste into the PhoneBook class above the main()// A method to add one new instance of Person class to the contacts
public static void add() {
x = contact.length;
temp = new Person[x + 1];
if(contact != null) {
System.arraycopy(contact,0,temp,0,Math.min(x,temp.length));
}
contact = temp;
contact[x] = new Person((x - 1), name, phone, email);
}
Inside the main() -
try {
// all the rest of your code goes here
} catch(IOException ex) {
System.out.println("Error: " + ex.getMessage());
} catch(Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
// process// do (while not quit)// ask the user (A)dd, (C)hange, (D)elete, (L)ist, or (Q)uit// get user option// switch case user option// if (A)dd// get new name, phone, and email from user// add a new Person object// end if// if (C)hange// get changed information (name, phone, or email) from user// change existing Person object// end if// if (D)elete// ask the user which one to delete// get one from user// delete one existing Person object// end if// if (L)ist// display all existing Person objects// end if// end switch case// end do while not quit
Each suite having 13 cards (King Queen Jack 10 9 8 7 6 5 4 3 2 Ace)
The objective of the game is to win all cards
The deck is divided evenly among the players
Cards are dealt face down
In unison, each player reveals the top card of their deck
The player with the higher card takes both of the cards played
Winning cards are added to the winner's stack
Aces are high and suits are ignored
For our simplified version -
Aces are low (value = 1)
Play only one round
Count how many times each player shows a higher card
Prepare -
Create a [F]ile [N]ew Java Application project named Kriegspiel
Be sure to name the project before you save it
Save to your Z:/java folder
Task 1 (Tuesday) - Classes for Deck and Card, Main -
Create the project main() and copy from codeProject.com - (just the inside of the main() method)
Create a new Class file named Deck and copy from codeProject.com - (just the part Array Example Number 2)
Create a new Class file named Card and copy from hws.edu - (the complete Card class)
EDIT THE DECK file as follows -
// Change the first line of the Deck() constructor method:i = 0;
// Change the "a" loop: for (int a=0; a<=12; a++) {
// Change the "b" loop: for (int b=0; b<=3; b++) {
// Change the statement inside the a-b loop: cards[i] = new Card((a + 1), b);
// Add a line after the loop:i = 51;
// pseudocode in main// declare deck// declare C// declare two Arrays of class Card hand1 and hand2// initialize both hands to new Card[26]// declare int variables: player1, player2, tie, i// declare boolean variable: even// loop while deck.getTotalCards() not equal 0// set C = deck.drawFromDeck()// if even is true// set hand1[i] to C// else// set hand2[i] to C// increment i// end if// set even to not even// loop for half the cards// display each card in each hand// end loop// display a line of "================"// loop for half the cards// if value of card in hand1 is greater than value of card in hand2// increment player1// else if value of card in hand2 is greater than value of card in hand2// increment player2// else// increment tie// end if// end loop// display values in player1 and player2
Save and Test the main()
Task 3 (Wednesday) - Continue the Kriegspiel game -
Logic -
// compare the first card in each hand// move both cards to the end of the winner's hand// remove the first card from each hand// while both first cards are the same value// compare the next two cards// continue while both cards are the same value// when one card is higher// move both cards to the end of the winner's hand// remove all moved cards from each hand// end when// end while// game ends when one hand has no remaining cards// (value of one hand [0] is null)
// copy and paste under the package
import java.util.Random;
import java.util.Scanner;
// pseudocode in the main()// create a new rand of type Random// create a new stdIn of type Scanner(System.in)// create a new variable r as type int (random computer number)// assign r a random number between 1 and 100 (inclusive)// create a new variable g as type int (guess)// tell the user to try to guess a number between 1 and 100// do loop// tell the user to guess// save the user guess to variable g// if g is greater than r// tell the user "Too High"// end if// if g is less than r// tell the user "Too Low"// end if// if g is equal to r// tell the user "You guessed my number: " + r// end if// loop while g not equal to r
Advanced -
Keep track of how many guesses the player has used
Limit the player to seven (7) guesses
Let the player try again
Keep track of how many times the player has played and how many wins (7 or less guesses)
Thursday, 03/22/18 - School Closed - Snow
Wednesday, 03/21/18 - School Closed - Snow
33) Tuesday, 03/20/18 - Java Object-Oriented Bank Account 32) Monday, 03/19/18 - Java Object-Oriented Bank Account
Project - BankAccount -
Concept -
Real world bank accounts
Banks track personal information and account balances
You can check your balance, deposit money, withdraw money
Create a Netbeans Java object-oriented project to simulate a bank account
Each new account is an object with identity, state, and behavior -
Identity - an account number
State - account balance
Behavior - methods to check balance, deposit, withdraw
Works good so far, but very inefficient hard coding account names as "a1", "a2", etc.
Has to be a better way, yes?
Array of Accounts!
Definitions (reminder) -
Array - A single variable that can hold many values of a single data type
Class - A blueprint of the bank account, with properties for balance and methods to check balance, deposit, withdraw
Object - An instance of a Class, has identity, state, and behavior, and works kind of like a complex variable
Array of Objects - A single variable where all of the elements are of the same Class
A set of method functions to perform processes when called
A loop so the user can choose to -
[B] - Check current balance
[D] - Deposit funds
[W] - Withdraw funds
[X] - Exit
Data Storage -
Account information (acctNum and balance) stored in a text file called "bank.txt"
When the program starts, read existing data from the file into the Array of accounts
When the program exits, write new data back to the file from the Array of accounts
Copy Code - only if you need it - be careful where you paste it -
Account.java Class File Code
// cut and paste into the Account.java class file
// global variables
private int acctNum = 0;
private String name = "";
private double balance = 0.0;
// constructor method with no parameter variables
Account() {
acctNum = 0;
name = "";
balance = 0.0;
}
// constructor method with parameter variables
Account(int n, String s, double b) {
acctNum = n;
name = s;
balance = b;
}
// other methods as named
public void setBalance(double b) {
balance = b;
}
public double getBalance() {
return balance;
}
public void setName(String s) {
name = s;
}
public String getName() {
return name;
}
public void deposit(double d) {
balance += d;
}
public void withdraw(double w) {
if(balance >= w) {
balance -= w;
} else {
System.out.println("Insufficient Funds");
}
BankAccount.java global variables and other methods above the main() method
// global variables
static Scanner stdIn = new Scanner(System.in);
static String action = "";
static double amount = 0.0;
static int acctNum = 0;
static Account[] accts = new Account[100];
static boolean another = true;
static String dummy = "";
static String str = "";
static int dotPos = 0;
// other methods as named
public static int getAccountNumber() {
int n = 0;
do {
System.out.print("Enter Account Number: ");
n = stdIn.nextInt();
} while(n < 0 || n > 100);
dummy = stdIn.nextLine();
return n;
}
public static void showBalance(int a) {
System.out.println("Account: " + acctNum + ", Balance: " + accts[acctNum].getBalance());
}
public static void balance() {
acctNum = getAccountNumber();
showBalance(acctNum);
}
public static void deposit() {
acctNum = getAccountNumber();
System.out.print("Deposit how much? ");
amount = stdIn.nextDouble();
dummy = stdIn.nextLine();
accts[acctNum].deposit(amount);
showBalance(acctNum);
}
public static void withdraw() {
acctNum = getAccountNumber();
System.out.print("Withdraw how much? ");
amount = stdIn.nextDouble();
dummy = stdIn.nextLine();
accts[acctNum].withdraw(amount);
showBalance(acctNum);
}
BankAccount.java code inside the main() method
try {
another = true;
// for all accounts// accts[i] = new Account()// end for// create a FileReader fr for "bank.txt"// create a BufferedReader br from fr// while((str = br.readLine()) != null)// set dotPos to str index of ":"// set acctNum to str substring 0 to dotPos// set amount to str substring dotPos + 1// for accts element acctNum setBalance() to amount// end while
do {
System.out.print("Select [B]alance, [D]eposit, [W]ithdraw, or e[X]it: ");
action = stdIn.nextLine().toUpperCase();
switch(action) {
case "B": balance(); break;
case "D": deposit(); break;
case "W": withdraw(); break;
case "X": another = false; break;
default: System.out.println("Invalid Entry");
}
//System.out.println("Action = " + action);
} while (another);
// create a FileWriter fw for "bank.txt"// create a BufferedWriter bw from fw// for all accounts// if the account balance is greater than zero// write the account number and the account balance// end if// end for// close the BufferedWriter
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
Advanced -
Format output currency
Display all account numbers and balances in a loop
Read accounts from a text file when starting the program
Write accounts data to a text file when ending the program
31) Friday, 03/15/18 - My Favorites Website
30) Thursday, 03/14/18 - My Favorites Website
29) Wednesday, 03/14/18 - My Favorites Website
Adobe Dreamweaver -
A proprietary web development tool owned by Adobe Systems
Involving two numbers, the base b and the exponent n
When n is a positive integer, exponentiation corresponds to repeated multiplication of the base
b^n is the product of multiplying n bases
Prepare -
Create a [F]ile [N]ew Java Application project named Power
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
// pseudocode Tell the user what to do Get a number n from the user Get an exponent p from the user Call a recursive funtion pow() The function will receive two parameter values - int n and int p The calling statement will pass two argument values n and pn and p in the main() are different variables from n and p in the recursive functionThe values are the same, but the RAM memory addresses are different Write a recursive function pow() - Two parameters - int n and int p If p is greater than 1, return n times pow() decrement p Return n Save and test using numbers you know - 2 ^ 2 = 4 2 ^ 3 = 8 2 ^ 8 = 256 4 ^ 5 = 1,024 10 ^ 9 = 1,000,000,000 10 ^ 10 = 1,410,065,408 - huh?????
Advanced -
Format with commas
Explain why 10 ^ 10 should have been 10,000,000,000 but did not work
Given two or more positive integers, the largest positive integer that divides evenly into all
Alternatively called greatest common factor (gcf), highest common factor (hcf), greatest common measure (gcm), or highest common divisor
Prepare -
Create a [F]ile [N]ew Java Application project named GreatestCommonDivisor
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
// pseudocode Tell the user what to do Get two numbers n1 and n2 from the user Ensure that n1 is larger than n2, otherwise switch them Call a recursive funtion gcd() The function will receive two parameter values - int n and int The calling statement will pass two argument values n and pn and p in the main() are different variables from n and p in the recursive functionThe values are the same, but the RAM memory addresses are different Write a recursive function pow() - Two parameters - int n and int p If p is greater than 1, return n times pow() decrement p Return n Save and test using numbers you know - 2 ^ 2 = 4 2 ^ 3 = 8 2 ^ 8 = 256 4 ^ 5 = 1,024 10 ^ 9 = 1,000,000,000 10 ^ 10 = 1,410,065,408 - huh?????
Advanced -
27) Monday, 03/12/18 - Java Recursive Factorial!
Project - Factorial -
Concept -
Factorial - n! (n factorial) is the product of all positive integers less than or equal to n
Prepare -
Create a [F]ile [N]ew Java Application project named Factorial
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
The user will enter a positive non-zero integer n between 1 and 16
Use a recursive loop to display the numbers and the factorial of n
Advanced -
Format the output factorial number with commas (eg: 123,456,789)
What is the highest number the user can enter before the program crashes?
Do what you can to prevent a crash?
26) Friday, 03/09/18 - Java Object-Oriented Bank Account with an Array and a Loop 25) Thursday, 03/08/18 - 90 MINUTE DELAYED OPENING - 24) Wednesday, 03/07/18 - Java Object-Oriented Bank Account with a Class
See Monday, 03/19/18 - Java Object-Oriented Bank Account
23) Tuesday, 03/06/18 - Java Career Steps using FileWriter/BufferedWriter
Project - CareerSteps -
Concept -
The file "careerSteps.txt" which is missing line numbers
Read the file in one-line-at-a-time
Prefix each line with a sequential line number
Write corrected lines to a file named "careerStepsFixed.txt"
Prepare -
Create a [F]ile [N]ew Java Application project named CareerSteps
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Read each line of the input file using FileReader/BufferedReader
Prefix each line with a sequential line number
Write each fixed line to the output file using FileWriter/BufferedWriter
Example -
try {
Reader fileReader = new FileReader("careerSteps.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
Writer fileWriter = new FileWriter("careerStepsFixed.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// pseudocode:// declare an integer variable lineNumber start at 1// use a loop to read all lines in the input file// prefix each input line with lineNumber// write the new line to the output file// increment lineNumber// end loop
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
Advanced -
If you go past 10 lines, how would you correctly line up the digits?
22) Monday, 03/05/18 - Java Gettysburg using FileReader/BufferedReader
Project - Gettysburg -
Concept -
Read the file "gettysburg.txt"
Use "System.out.println" to display it
Prepare -
Create a [F]ile [N]ew Java Application project named Gettysburg
Given an Array of positive non-zero integers, compute and display the minimum number, maximum number, and average of numbers
Prepare -
Create a [F]ile [N]ew Java Application project named MinMaxMean
Be sure to name the project before you save it
Save to your Z:/java folder
Process -
Generate an Array of 100 positive non-zero integers between 1 and 100
Determine and display the minimum number
Determine and display the maximum number
Determine and display the mean number
Task -
Import -
// copy and paste// under the package
import java.util.Random;
Inside the main() - pseudocode
Create an instance variable rand of type Random
Create an Array variable nums of type int
Create a variable min of type int initialize to 1000
Create a variable max of type int initialize to 0
Create a variable sum of type int initialize to 0
Create a variable mean of type int initialize to 0
Loop 100 times
Initialize each element of Array nums to a random number between 1 and 100
End Loop
Loop 100 times
If nums element is less than min
replace min value with nums element value
End If
If nums element is greater than max
replace max value with nums element value
End If
Add nums element to sum
End Loop
Divide sum by 100 and replace value in mean
Display "Minimum: " + min
Display "Maximum: " + max
Display "Mean: " + mean
Save and test
Advanced -
Let the user choose the size of the Array nums
Include negative numbers and zero in the random process - What should the mean be?
19) Wednesday, 02/27/18 - Java Tic Tac Toe Game 18) Tuesday, 02/27/18 -
Project - TicTacToe -
Concept -
Tic tac toe is played on a 3x3 grid game board
The object is to get three in a row horizontally, vertically, or diagonally
The first player is X and the second is O
Player X always goes first
Players alternate placing one X or one O on the game board
A win is when one player has three-in-a-row
Eight (8) different ways to get three-in-a-row -
Three (3) horizontal rows - top, middle, bottom
Three (3) vertical columns - left, center, right
Two (2) diagonigals - top left to bottom right, top right to bottom left
We must check all eight (8) possibilities each time a play is made
Ties occur when all nine squares are filled but neither player has three in a row
Prepare -
Create a [F]ile [N]ew Java Application project named TicTacToe
Be sure to name the project before you save it
Save to your Z:/java folder
Task - Wednesday -
Method seekWinner() -
// copy and paste// before the main()
public static void seekWinner() {
winner = false; // reset before each test
if(b[0][0] != ' ' && b[0][0] == b[0][1] && b[0][1] == b[0][2]) { winner = true; } // top row
// center row...
// bottom row...
if(winner) {
switchXoro();
System.out.println("Winner is " + xoro);
}
}
Call seeWinner() - AFTER EVERY PLAY (stdIn)
Save and Test
Advanced -
How would you prevent additional plays after a winner?
How would you Reset the game?
Task - Tuesday -
Import -
// copy and paste// under the package
import java.util.Scanner;
Global Variables - BEFORE THE MAIN() -
// copy and paste// before the main()
static char[][] b = new char[3][3];
static int r = 0, c = 0, i = 0;
static char xoro = 'x';
Method - BEFORE THE MAIN() -
// copy and paste// before the main()
public static void show() {
System.out.println("Tic Tac Toenail");
System.out.println("1|2|3 " + b[0][0] + "|" + b[0][1] + "|" + b[0][2]);
System.out.println("-|-|- -|-|-");
System.out.println("4|5|6 " + b[1][0] + "|" + b[1][1] + "|" + b[1][2]);
System.out.println("-|-|- -|-|-");
System.out.println("7|8|9 " + b[2][0] + "|" + b[2][1] + "|" + b[2][2]);
System.out.println("Player " + xoro + ", your turn");
System.out.println("Press a number 1-9 to play (-1 to exit)");
}
Inside the main() - pseudocode
create the stdIn Scanner object
create an integer variable n and initialize to 0 (zero)
initialize populate each element in the b board array to space char
begin a while n > -1 loop (-1 will end the game)
read a value for n from the keyboard
if n < 0 break;
save and test
if n is between 1 and 9 inclusive (0 is no good, 10 is no good)
save and test
decrement n (make it one less)
set r equal to n divided by 3 (r will be 0, 1, or 2)
set c equal to n modulus 3 (c will be 0, 1, or 2)
if board square element [r][c] is blank
change board square to value in xoro
if xoro is 'x' change to 'o'
if xoro is 'o' change to 'x'
save and test
else
tell user invalid number
save and test
end if
else
tell user invalid play
save and test
end if
save and test
end loop
Advanced -
Determine how and when to test for a winner
17) Monday, 02/26/18 - Java Multidimentional Array and Loop Practice
Modify the ArrayPractice Java project -
Declare a 3-by-3 2D array for a tic-tac-toe game board Display the tic-tac-toe board Declare an 8-by-8 2D array to hold pieces on a chess game board Display the chess board Declare an array of seating prices for the Lakewood Strand Theater Center Mezzanine Declare a 2-by-4 2D array to hold lengths of strips of wood Declare a 12-by-12 array for a multiplication table Populate the values into the multiplication table Display the multiplication table
Advanced -
Populate the check board with checkers pieces 'B' for black, 'W' for white, ' ' for empty
16) Friday, 02/23/18 - Java Array and Loop Practice
Modify the ArrayPractice Java project -
Display the title for Star Wars® Episode 5 Display all Star Wars® Episode titles Display all Star Wars® Episode titles and release dates Display all Star Wars® Episode titles and gross profits Display all
15) Thursday, 02/22/18 - Java Array and Loop Practice
Modify the ArrayPractice Java project -
Display the owner of boat in slip # 5 (index # 4) Display which cars by number are in which positions on the car carrier Count and display how many "Red" cups
14) Wednesday, 02/21/18 - Java Array and Loop Practice
Project - ArrayPractice -
Concept - Create a new Java Project to practice using the FOR loop
Prepare -
Create a [F]ile [N]ew Java Application project named ArrayPractice
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Import -
// under the package
import java.util.Scanner;
stdO() and stdOut() - Add methods to simplify output -
public static void stdO(String s) {
System.out.print(s); // Stay on same output line
}
public static void stdOut(String s) {
System.out.println(s); // Move to next output line
}
Save and Test between each step
Pseudocode - Use a FOR loop -
// Declare an Array nums// Instanciate nums with numbers 1 - 10// Declare and instanciate nums on the same line// Declare a variable len and get the size of nums// Display the values in Array nums// Declare an Array fib size 20// Use a loop to populate fib with the first 20 Fibonacci numbers
Save and Test between each step
Advanced -
Declare and instanciate an Array containing all 26 uppercase letters
Concept - Create a new Java Project to practice using the FOR loop
Prepare -
Create a [F]ile [N]ew Java Application project named LoopPractice
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Import -
// under the package
import java.util.Scanner;
stdO() and stdOut() - Add methods to simplify output -
public static void stdO(String s) {
System.out.print(s); // Stay on same output line
}
public static void stdOut(String s) {
System.out.println(s); // Move to next output line
}
Save and Test between each step
Pseudocode - Use a FOR loop -
// Print numbers 1 to 10// Print numbers 10 to 1// Print numbers 2 to 20// Print 20 characters in the Fibonacci sequence// Ask the user how many Fibonacci numbers to print// Use BREAK to stop the sequence early// Print your name five times on the same line// Print your name five times on the different lines
12) Friday, 02/16/18 - Java Month and Day-of-Week using Switch
Project - DayOfWeek -
Concept - Modify the DayOfWeek Java Project use SWITCH statement to display name of month and name of day-of-week
Prepare -
Create a [F]ile [N]ew Java Application project named DayOfWeek
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Import -
// under the package
import java.util.Scanner;
import java.util.Calendar;
// import java.text.DecimalFormat;
stdOut() - Add the method to simplify output -
public static void stdOut(String s) {
System.out.println(s);
}
Calendar Object -
Calendar cal = Calendar.getInstance(); // declare cal as an object of Calendar class
Calendar DAY_OF_MONTH -
int dd = cal.get(Calendar.DAY_OF_MONTH); // grab today's date as a number using Calendar
stdOut("Day of Month: " + dd); // display the day of month number
Save and Test
Calendar DAY_OF_WEEK -
int dow = cal.get(Calendar.DAY_OF_WEEK); // grab day of week as a number
stdOut("Day of Week: " + dow); // display the day of week number
Save and Test
Calendar MONTH -
int mm = cal.get(Calendar.MONTH); // grab this month as a number
stdOut("Month of Year: " + mm); // display the month number// why is the month number incorrect? and what can we do to fix it?
Save and Test
Calendar Year -
// grab and display year on-your-own
Save and Test
SWITCH - Display the name of the day of the week -
String dowName = ""; // declare a String for the name of the day of the week
switch ( dow ) { // switch ( date_variable )
case 1: dowName = "Sunday"; break;// assign "Sunday" to variable; break;
case 2: dowName = "Monday"; break;// assign "Monday" to variable; break;// continue for "Tuesday" through "Saturday"
default: dowName = "Something went horribly wrong";// assign "Something went horribly wrong" to variable// close the switch segment
}
Save and Test
SWITCH - Display the name of the month -
// see how far you can get on your own
Save and Test
Advanced -
Build and display an entire date statement - "Friday, February 16, 2018"
Concept - Modify the Grades Java Project to use a SWITCH statement instead of the nested IF statement to print a note based on a letter grade
Prepare -
Modify a [F]ile [N]ew Java Application project named Grades
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Pseudocode -
// pseudocode // user enters a number grade // computer displays a letter grade // modify to also save the letter grade into a variable // display a message based on the letter grade // switch on grade // case 'A' display "Excellent" and break // case 'B' display "Well Done" and break // case 'C' display "Good Job" and break // case 'D' display "Keep Trying" and break // default display "What Can I Do to Help?"
Advanced -
Is it possible to do the numbergrade to lettergrade using SWITCH?
If not, why not?
10) Wednesday, 02/14/18 - Java Grades, part II
Project - Review and complete the Change II project from Tuesday
Project - Grades, part II -
Concept - Modify the Grades Java Project to print a note based on a letter grade
Prepare -
Modify a [F]ile [N]ew Java Application project named Grades
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
stdOut() - Add the method to simplify output -
public static void stdOut(String s) {
System.out.println(s);
}
Pseudocode -
// pseudocode // user enters a number grade // computer displays a letter grade // modify to also save the letter grade into a variable // display a message based on the letter grade // if letter grade is 'A' display "Excellent" // if letter grade is 'B' display "Well Done" // if letter grade is 'C' display "Good Job" // if letter grade is 'D' display "Keep Trying" // if letter grade is 'F' display "What Can I Do to Help?"
Advanced -
Can you do this in the subroutine?
Thursday we will switch case statement - think about it today
09) Tuesday, 02/13/18 - Mr. Clarke on Field Trip - Java Change, part 3, don't print zero values
Project - Change -
Concept - Modify the Change Java Project to cleanup the output
Prepare -
Modify a [F]ile [N]ew Java Application project named Change
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
stdOut() - Add the method to simplify output -
public static void stdOut(String s) {
System.out.println(s);
}
Pseudocode -
// pseudocode // currently prints amount of 20's, 10's, etc... // modify to NOT display any 0 amounts // do not display "0 20's" or "0 Quarters" // try your best // we will review on Wednesday when I return
Advanced -
Can you do this in the subroutine?
Can you write this with a switch case statement
08) Monday, 02/12/18 - Java BMI (Body Mass Index), Part 2, IF
Project - BMI -
Concept -
Body mass index (BMI) is commonly used by health and nutrition professionals to estimate human body fat in populations
Calculate the BMI and tell the user if they are overweight and how much
Prepare -
Create or Modify a [F]ile [N]ew Java Application project named BMI
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Determine BMI health and display to the user - use an ested IF statement -
// use this scale: // < 18.5 underweight// 18.5 to 24.9 normal// 25.0 to 29.9 overweight// 30.0 to 35.0 obese I mild// 35.0 to 39.9 obese II high// > 40.0 obese III extreme
If the user BMI is high, tell the user how much BMI high
Figure a way to tell the user how much weight they should lose
07) Friday, 02/09/18 - Java BMI (Body Mass Index)
Project - BMI -
Concept -
Body mass index (BMI) is commonly used by health and nutrition professionals to estimate human body fat in populations
Compute BMI by taking the individual's weight (mass) in kilograms and dividing it by the square of their height in meters
Prepare -
Create a [F]ile [N]ew Java Application project named BMI
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
// import the Scanner// create stdIn// tell the user what the program will do// tell the user to enter weight in kilograms// read the user weight in kilograms (what data type?)// tell the user to enter height in meters// read the user height in meters (what data type?)// calculate the BMI by dividing weight by height2 (use PEMDAS)// display BMI to the user with explanation ("Your BMI is " + bmi)
Scanner -
// under the package
import java.util.Scanner;
import java.text.DecimalFormat;
stdIn - (use instead of "keyboard") -
// inside the main { } body
Scanner stdIn = new Scanner(System.in);
Input height in feet and inches and convert to meters
06) Thursday, 02/08/18 - Java Change Version 2 using Methods
Project - Change2 -
Concept -
Rewrite the Change program using one (1) (???) method function
Really??? Just one (1) method function??? How the heck???
How many lines can we save???
Prepare -
Create a [F]ile [N]ew Java Application project named Change2
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Scanner -
// under the package
import java.util.Scanner;
import java.text.DecimalFormat;
stdIn - (use instead of "keyboard") -
// inside the main { } body
Scanner stdIn = new Scanner(System.in);
makeChange() - define a Java subroutine method -
// outside the main { } body// pseudocode// declare three (3) parameter variables:// double c to hold the current change due// int x to hold the current paper or coin amount// String s to hold the name of the current paper or coin// declare a local variable hm// set the value of hm to be (int)( c / x )// display hm concatenate s// change c modulus by x// return c
Statements - Inside the main -
// inside the main { } body// pseudocode// declare a variable stdIn as type Scanner// tell the user to enter purchase price// save into a variable double price// tell the user to enter amount tendered// save into a variable double tendered// calculate double change as tendered minus price// show the user the change due amount// call the method makeChange passing arguments change, 20, " Twenties"// call the method makeChange passing arguments change, 10, " Tens"// call the method makeChange passing arguments change, 5, " Fives"// call the method makeChange passing arguments change, 1, " Ones"// tell the user thank you for coming and have a nice day
Advanced -
Coins -
// increase change by 100 to remove the decimal point// ($.25 becomes 25 cents -- easier to modulus)// call the method makeChange passing arguments change, 25, " Quarters"// call the method makeChange passing arguments change, 10, " Dimes"// call the method makeChange passing arguments change, 5, " Nickels"// display Math.round( change ) concatenate " Pennies"
05) Wednesday, 02/07/18 - Java Practice Methods (Subroutines and Functions)
Project - MethodPractice -
Concept - Practice defining and calling Java methods
Prepare -
Create a [F]ile [N]ew Java Application project named MethodPractice
Be sure to name the project before you save it
Save to your Z:/java folder
Task -
Scanner -
// under the package
import java.util.Scanner;
import java.text.DecimalFormat;
stdIn - (use instead of "keyboard") -
// inside the main { } body
Scanner stdIn = new Scanner(System.in);
sayHello() - define a Java subroutine method -
// outside the main { } body// pseudocode// catch one String parameter// display "Hello, " and the parameter
Statements - Inside the main -
// inside the main { } body// pseudocode// tell the user to enter first name// read the user first name from the keyboard// assign to a String variable named "fName"// call the Java subroutine method "sayHello()" passing the variable "fName" as an argument
min() - define a Java subroutine method -
// outside the main { } body// pseudocode// catch two integer parameters// return the smaller value
Statements - Inside the main -
// inside the main { } body// pseudocode// tell the user to enter two integer values// read the first integer value from the keyboard// assign to an integer variable named "num1"// read the second integer value from the keyboard// assign to an integer variable named "num2"// call the Java subroutine method "min()" passing both "num1" and "num2" as an argument
swapper() - define a Java subroutine method -
// outside the main { } body// pseudocode// catch two integer parameters// swap the two parameter values
Statements - Inside the main -
// inside the main { } body// pseudocode// use the existing "num1" and "num2" values// display both "num1" and "num2" back to the user before swapping// call the Java subroutine method "swapper()" passing both "num1" and "num2" as an argument// display both "num1" and "num2" back to the user after swapping
Advanced -
Define a Java method function "max()", catch two parameters, return and display the larger
Define a Java method function "avg()", catch three parameters, return and display the average
04) Tuesday, 02/06/18 - Java Practice Data Types and Variables 03) Monday, 02/05/18 - Java Make Change
The only way to learn a new programming language is to program in it. ~
Dennis Richie
Project - Change -
Concept -
You make a purchase and pay cash
The cleck enters the amount of the purchase and the amount tendered
The computer determines how much change you receive
The computer displays how many dollars (20's, 10's, 5's, 1's) and how many quarters, dimes, nickels, pennies
Project Name: "Change", [Browse] and save to your "Z:/Java-css/" folder, [Finish]
Don't Change the Package name or Public Class name
Task Tuesday -
Add below existing code
Based on change amount, determine how many paper bills twenties, tens, fives, ones
Based on change amount, determine how many quarters, dimes, nickels, pennies
Pseudocode -
// twenties is change divided by 20
// change is change mod 20
// tens is change divided by 10
// change is change mod 10
// fives is change divided by 5
// change is change mod 5
// ones is change divided by 1
// change is change mod 1
// change is change times 100
// quarters is change divided by 25
// change is change mod 25
// dimes is change divided by 10
// change is change mod 10
// nickels is change divided by 5
// change is change mod 5
// pennies is change
// display all values with explanations
// $57.57 should diplay as:
// "2 Twenties, 1 Ten, 1 Fives, 2 Ones, 2 quarters, 0 dimes, 1 nickels, 2 pennies"
Task Monday -
Add a line imediately below the package -
import java.util.Scanner; // new line 6
Find the line "// TODO code application logic here" and add your code below -
Scanner keyboard = new Scanner(System.in); // keyboard is an object of type Scanner
// Pseudocode
// Tell the user to enter purchase price
// Read the user keyboard entry
// Tell the user to enter amount tendered
// Read the user keyboard entry
// Calculate the change due
// Display the change due
Advanced -
Format the change output to two decimal points
02) Friday, 02/02/18 - Mr. Clarke Out Sick - Java Practice
Project Name: "Payroll", [Browse] and save to your "Z:/Java-css/" folder, [Finish]
Don't Change the Package name or Public Class name
Edit the code -
Change the author name to your name and add today's date
Add a line imediately below the package -
import java.util.Scanner; // new line 6
Find the line "// TODO code application logic here" and add your code below -
Scanner keyboard = new Scanner(System.in); // keyboard is an object of type Scanner
System.out.println("Payroll Project"); // Tell the user what project
System.out.print("Enter Hours Worked: "); // Tell the user what to type
double hours = keyboard.nextDouble(); // Get user input
System.out.print("Enter Pay Rate: "); // Tell the user what to type
double rate = keyboard.nextDouble(); // Get user input
double gross = hours * rate; // Calculate gross as hours times rate
double taxes = gross * 0.3; // Calculate taxes as 30% of gross
double net = gross - taxes; // Calculate net as gross minus taxes
System.out.println("Gross Pay: $" + gross); // Display answer to user
System.out.println("Taxes: $" + taxes); // Display answer to user
System.out.println("Net Pay: $" + net); // Display answer to user
Run the code -
Click the ▶ Run Project icon
Click [R]un, [R]un Project on the menu
Press and release the [F6] key
Test with 10 hours worked and 10 pay rate
Gross should be 100, taxes should be 30, net should be 70