COSC 236 Web Site
• You will always find the course material at:
http://www.class-notes.us or
http://www.class-notes.info or
http://www.lecture-notes.tripod.com
From this site you can click on the COSC-236 tab to download the PowerPoint lectures, the Quiz solutions and the Laboratory assignments.
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
2
Review for Final Exam (Wednesday 12/17/14 3-5pm)
• The Final Exam will cover the entire course
• The Exam will be similar to the in-class portion of the Midterm
•You should review Lecture 13, the review for the Midterm
• This review will cover Lectures 14 through 25
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
4
Review of Quiz 13
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
6
There are at least two ways to solve this problem using material
that we have covered in class so far:
• The one based on the material in Lecture 13 is to make use of a
for loop to implement a cumulative algorithm
• The algorithm is to copy character by character from text to
temp checking for when the loop counter i becomes equal to
index to trigger the insertion of newText
• After the new text is inserted, the remainder of text is copied
Review of Quiz 13
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
7
public static String replaceAt(int index, String text, String newText) {
int length = text.length();
String temp = "";
if (index < 0 || index >= length) {return text; } //Check for out of range index
else {
for (int i = 0; i < length; i++) {
if (i == index) {temp = temp + newText; }
else {temp = temp + text.charAt(i);}
}
}
return temp;
}
Review of Quiz 13
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
9
There are at least two ways to solve this problem using material
that we have covered in class so far:
• The second technique is actually simpler, but is not based on
the material in Lecture 13 on cumulative algorithms
• The algorithm uses the substring method to specify the initial
text from text, then concatenate the newText, and finally use
the substring method to complete the text.
• This is a simpler method, but does not demonstrate the
cumulative algorithm we are studying.
Review of Quiz 13
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
10
public static String replaceAt(int index, String text, String newText) {
int length = text.length();
String temp = "";
if (index < 0 || index >= length) {return text;} //Check for out of range index
else {temp = text.substring(0, index) + newText + text.substring(index+1, length);}
return temp;
}
Review of Quiz 13 (Complete Program 2)
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
11
import java.util.*; // for Scanner
public class Quiz13a {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String text = "0123456789"; // This is the text that will be modified
System.out.println("\ntext to be modified = " + text);
System.out.print("Enter index of the character you wish to replace in the text: ");
int index = console.nextInt(); // Read index from console
console.nextLine(); // Clear the console for next read
System.out.println("\nEnter the String you wish to replace that character with: ");
String newText = console.nextLine(); // Read the new text
System.out.println();
text = replaceAt(index, text, newText); // Call the replace method
System.out.println("Modified text = " + text); // Print modified text to console
}
public static String replaceAt(int index, String text, String newText) {
int length = text.length();
String temp = "";
if (index < 0 || index >= length) {return text;} //Check for out of range index
else {temp = text.substring(0, index) + newText + text.substring(index+1, length);} return temp;
}
}
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
13
This should be a very easy Quiz, if you approach it one line at a
time:
• First get the Heading of the table correct
• Then do one column at a time getting each column correct
before moving to the next
• After all columns are done, you have a completed program
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
14
Start with the heading of the table:
Two approaches
• Use printf() with “%4s%12s %12s %12s %12s”
• Use printf() with the entire heading exactly in quotes:
“Year Yearly Quarterly Monthly Continuously”
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
15
Use printf() with “%4s%12s %12s %12s %12s” :
import java.util.*; // for Scanner
public class Quiz14_1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the principle (amount deposited.) P = ? ");
double p = console.nextDouble();
System.out.print("Enter the yearly interest rate. r = ? ");
double r = console.nextDouble();
r = r/100;
System.out.print("Enter the time in whole number of years. t = ? ");
int t = console.nextInt();
System.out.printf("\n%4s%12s %12s %12s %12s\n", "Year", "Yearly", "Quarterly", "Monthly", "Continuously");
}
}
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
16
Use printf() with “%4s%12s %12s %12s %12s” :
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
17
Use printf(“Year Yearly Quarterly Monthly Continuously”):
import java.util.*; // for Scanner
public class Quiz14_2 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the principle (amount deposited.) P = ? ");
double p = console.nextDouble();
System.out.print("Enter the yearly interest rate. r = ? ");
double r = console.nextDouble();
r = r/100;
System.out.print("Enter the time in whole number of years. t = ? ");
int t = console.nextInt();
System.out.printf("\nYear Yearly Quarterly Monthly Continuously\n");
}
}
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
18
Get the first column to line up:import java.util.*; // for Scanner
public class Quiz14_3 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the principle (amount deposited.) P = ? ");
double p = console.nextDouble();
System.out.print("Enter the yearly interest rate. r = ? ");
double r = console.nextDouble();
r = r/100;
System.out.print("Enter the time in whole number of years. t = ? ");
int t = console.nextInt();
System.out.printf("\nYear Yearly Quarterly Monthly Continuously\n");
for (int n = 1; n <= t; n++) {
System.out.printf("%2d", n);
System.out.println();
}
}
}
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
19
Get the first column to line up:
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
20
Get the second column to line up:import java.util.*; // for Scanner
public class Quiz14_4 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the principle (amount deposited.) P = ? ");
double p = console.nextDouble();
System.out.print("Enter the yearly interest rate. r = ? ");
double r = console.nextDouble();
r = r/100;
System.out.print("Enter the time in whole number of years. t = ? ");
int t = console.nextInt();
System.out.printf("\nYear Yearly Quarterly Monthly Continuously\n");
for (int n = 1; n <= t; n++) {
System.out.printf("%2d", n);
System.out.printf(" $%,9.2f", p*Math.pow(1+r,n));
System.out.println();
}
}
}
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
21
Get the second column to line up:
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
22
Get the third column to line up:import java.util.*; // for Scanner
public class Quiz14_5 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the principle (amount deposited.) P = ? ");
double p = console.nextDouble();
System.out.print("Enter the yearly interest rate. r = ? ");
double r = console.nextDouble();
r = r/100;
System.out.print("Enter the time in whole number of years. t = ? ");
int t = console.nextInt();
System.out.printf("\nYear Yearly Quarterly Monthly Continuously\n");
for (int n = 1; n <= t; n++) {
System.out.printf("%2d", n);
System.out.printf(" $%,9.2f", p*Math.pow(1+r,n));
System.out.printf(" $%,9.2f", p*Math.pow(1+r/4,4*n));
System.out.println();
}
}
}
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
23
Get the third column to line up:
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
24
Get the fourth column to line up:import java.util.*; // for Scanner
public class Quiz14_6 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the principle (amount deposited.) P = ? ");
double p = console.nextDouble();
System.out.print("Enter the yearly interest rate. r = ? ");
double r = console.nextDouble();
r = r/100;
System.out.print("Enter the time in whole number of years. t = ? ");
int t = console.nextInt();
System.out.printf("\nYear Yearly Quarterly Monthly Continuously\n");
for (int n = 1; n <= t; n++) {
System.out.printf("%2d", n);
System.out.printf(" $%,9.2f", p*Math.pow(1+r,n));
System.out.printf(" $%,9.2f", p*Math.pow(1+r/4,4*n));
System.out.printf(" $%,9.2f", p*Math.pow(1+r/12,12*n));
System.out.println();
}
}
}
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
25
Get the fourth column to line up:
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
26
Get the last (5th) column to line up:import java.util.*; // for Scanner
public class Quiz14_7 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter the principle (amount deposited.) P = ? ");
double p = console.nextDouble();
System.out.print("Enter the yearly interest rate. r = ? ");
double r = console.nextDouble();
r = r/100;
System.out.print("Enter the time in whole number of years. t = ? ");
int t = console.nextInt();
System.out.printf("\nYear Yearly Quarterly Monthly Continuously\n");
for (int n = 1; n <= t; n++) {
System.out.printf("%2d", n); //1st column
System.out.printf(" $%,9.2f", p*Math.pow(1+r,n)); //2nd column
System.out.printf(" $%,9.2f", p*Math.pow(1+r/4,4*n)); //3rd column
System.out.printf(" $%,9.2f", p*Math.pow(1+r/12,12*n)); //4th column
System.out.printf(" $%,9.2f", p*Math.pow(Math.E,r*n)); //5th column
System.out.println();
}
}
}
Review of Quiz 14
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
27
Get the last (5th) column to line up:
Review of Quiz 15
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
28
Quiz 15: This Quiz is aimed at using random numbers and printing out a list separated by commas using the fencepost algorithm discussed in Lecture 14.
Write a complete program (class) that asks the user how many random numbers the user wants printed and then prints on a single line that number of random numbers. The random numbers will be integers in the range 2 through 12 inclusive. Each random number is separated by a comma and a space.
Here is what typical output from your program will look like:
NOTE: There should be no extra commas or spaces at the beginning or at the end of the list.
Review of Quiz 15
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
29
There are two issues addressed in Quiz 15:
• First is generating random integers between 2 and 12 inclusively
• The range is max – min + 1 = 12 – 2 + 1 = 11
• The minimum number is 2
• rand.nextInt(11) + 2
• The second is the fence-post algorithm to print out the random numbers with commas
between each number
• Print one random number before the for loop and leading commas in the for loop
• Print following commas in the for loop and one random number after the for loop
Review of Quiz 15
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
30
import java.util.*; // for Scanner
public class Quiz15 {
public static void main(String[] args) {
Random rand = new Random();
Scanner console = new Scanner(System.in);
System.out.print("How many random numbers would you like? ");
int number = console.nextInt();
System.out.print(rand.nextInt(11) + 2);
for (int n = 1; n <= number; n++) {
System.out.print(", " + (rand.nextInt(11) +2));
}
System.out.println();
}
}
Boiler Plate
Set up random numbersSet up scanner for input
Prompt and get inputPrint first fence post
Print line of number preceded by comma and spaceUse println to go to next line at end of program
Review of Quiz 15
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
31
QUESTION about the random numbers generated in Quiz 15:
• Would these number represent the throw of two dice?
• The range is correct: min = 2, max = 12
• The numbers are random
• Does rand.nextInt(11) + 2 simulate the roll of two
dice?
• NO: The numbers 2 through 12 are not equally likely!
Review of Quiz 15
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
32
QUESTION about the
random numbers
generated in Quiz 15:
• Would these number
represent the throw of
two dice?
• NO: The numbers 2
through 12 are not
equally likely!
rand.nextInt(6) + rand.nextInt(6) + 2
Review of Quiz 16
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
33
You were given the main program and were asked to write the two Boolean methods isPrime() and hasAnEvenDigit()
The method isPrime() was already written for you –although you were asked to improve it
The method hasAnEvenDigit() can be obtained by making modifications to hasAnOddDigit()
Review of Quiz 16
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
34
There are two issues addressed in Quiz 16:
• Modifying the ifPrime() method to make it more efficient
• Instead of the for loop going from 1 to n, it could go from 2 to n-1. The return
would then be changed to return factors == 0;
• The loop could run from 2 to n-1, but as soon as you found an integer that divided
into n, you would return a false so that it would not continue checking.
• The most efficient is to change the loop to run from 2 to Math.sqrt(n) and to return
a false as soon as you find an integer that divided into n
• Modifying hasAnOddDigit() to check for even digits.
• Change the statement if (n % 2 != 0) to if (n % 2 == 0)
Review of Quiz 16
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
35
public static boolean isPrime(int n) {
n = Math.abs(n); // take care of negative numbers
for (int i = 2; i*i <= n; i++) {
if (n % i == 0) {
return false;
}
}
Could also be: i <= Math.sqrt(n)
Review of Quiz 16
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
36
public static boolean hasAnEvenDigit(int n) {
n = Math.abs(n); // take care of negative numbers
while (n > 0) {
if (n % 2 == 0) { // check whether last digit is even
return true;
}
n = n / 10;
}
return false;
}
Review of Quiz 17
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
37
PART 1: You were given the program and asked to modify it to read the file Quiz17.java
You were to run the file and confirm the output as shown.
You were encouraged to copy and paste the program from the Quiz 17 assignment sheet.
Review of Quiz 17
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
38
PART 1: Only one minor change required:
import java.io.*; // for File
import java.util.*; // Java utilities
public class FileRead {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("Test.txt");
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns "
+ f.getAbsolutePath());
int count = 0;
while (input.hasNext()) {
String word = input.next();
count++;
}
System.out.println("total words = " + count);
}
}
Change "Test.txt" to "Quiz17.java"
Review of Quiz 17
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
39
PART 1: Only one minor change required:
import java.io.*; // for File
import java.util.*; // Java utilities
public class FileRead {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("Test.txt");
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns "
+ f.getAbsolutePath());
int count = 0;
while (input.hasNext()) {
String word = input.next();
count++;
}
System.out.println("total words = " + count);
}
}
import java.io.*; // for File
import java.util.*; // Java utilities
public class FileRead {
public static void main(String[] args) throws FileNotFoundException {
File f = new File(“Quiz17.java);
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns "
+ f.getAbsolutePath());
int count = 0;
while (input.hasNext()) {
String word = input.next();
count++;
}
System.out.println("total words = " + count);
}
}
Change "Test.txt" to "Quiz17.java"
Review of Quiz 17
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
40
PART 2: Modify the program to print out any comment lines and exclude them from the count
In class you were also told to add a comment at the beginning of the program:
// Report some basic information about a file.
Review of Quiz 17
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
41
// Report some basic information about a file.
import java.io.*; // for File
import java.util.*; // Java utilities
public class Quiz17 {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("Quiz17.java");
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns "
+ f.getAbsolutePath());
ADD Comment
Change file name
Review of Quiz 17
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
42
int count1 = 0;
int count2 = 0;
while (input.hasNext()) {
String word = input.next();
if (word.equals("//")) {
count2++;
String temp = input.nextLine();
System.out.println("Comment " + count2 + " = //" + " " + temp);}
else {count1++;}
}
System.out.println("total words excluding comments = " + count1
+ "\nThere are " + count2 + " comments.");
}
}
Set up counter for comments
Set up counter for words
Check token for comment
Review of Quiz 17
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
43
int count1 = 0;
int count2 = 0;
while (input.hasNext()) {
String word = input.next();
if (word.equals("//")) {
count2++;
String temp = input.nextLine();
System.out.println("Comment " + count2 + " = //" + " " + temp);}
else {count1++;}
}
System.out.println("total words excluding comments = " + count1
+ "\nThere are " + count2 + " comments.");
}
}
Increment comment counter
The rest of the line is comment
Print out comment number and comment
If not a comment, increment word counter
No change in the rest of the program
Review of Quiz 18
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
44
PART 1: Insert a while loop that allows the user to query whether or not a file exist (“q” to quit)
PART2: Insert a second while loop to print out the summary which was stored in a file in the first while loop
You were encouraged to copy and paste the program from the Quiz 18 assignment sheet.
Review of Quiz 18
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
45
PART 1: First while loop:
while (!name.equals("q")) {
File f = new File(name);
if (f.exists()) {
consoleOut.printf("File %s exists.\n", name);
file.printf("File %s exists.", name);
file.println();}
else {
consoleOut.printf("File %s DOES NOT exist.\n", name);
file.printf("File %s DOES NOT exist.", name);
file.println();}
Review of Quiz 18
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
46
while (summary.hasNextLine()) {
String line = summary.nextLine();
consoleOut.println(line);
}
PART 2: Second while loop:
Review of Quiz 19
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
47
User enters the number of test scores and then is prompted to enter each test score
Program calculates the mean, median, high and low score
The Weather Program of Lecture 18, slide 42 does most of what is needed. We need only to replace the day’s above average loop with the calculation of low, high and median
Review of Quiz 19
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
48
The Weather Program:// Reads temperatures from the user, computes average and # days above average.
import java.util.*;
public class Weather {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many days' temperatures? ");
int days = console.nextInt();
double[] temps = new double[days]; // array to store days' temperatures
double sum = 0;
for (int i = 0; i < days; i++) { // read/store each day's temperature
System.out.print("Day " + (i + 1) + "'s high temp: ");
temps[i] = console.nextDouble();
sum += temps[i];}
double average = sum / days;
int count = 0; // see if each day is above average
for (int i = 0; i < days; i++) {
if (temps[i] > average) {
count++;}
}
// report results
System.out.printf("Average temp = %.1f\n", average);
System.out.println(count + " days above average");
}
}
Arrays.sort(temps);
double median = 0;
if (temps.length % 2 == 1) {median = temps[temps.length/2];}
else {
median = (temps[temps.length/2] + temps[temps.length/2 - 1])/2;
}
System.out.printf(" High Score: %6.2f\n Mean Score: %6.2f\n", temps[temps.length-1], average);
System.out.printf("Median Score: %6.2f\n Low Score: %6.2f\n", median, temps[0]);
Replace this
Review of Quiz 19
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
49
The Weather Program:// Reads temperatures from the user, computes average and # days above average.
import java.util.*;
public class Weather {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many days' temperatures? ");
int days = console.nextInt();
double[] temps = new double[days]; // array to store days' temperatures
double sum = 0;
for (int i = 0; i < days; i++) { // read/store each day's temperature
System.out.print("Day " + (i + 1) + "'s high temp: ");
temps[i] = console.nextDouble();
sum += temps[i];}
double average = sum / days;
int count = 0; // see if each day is above average
for (int i = 0; i < days; i++) {
if (temps[i] > average) {
count++;}
}
// report results
System.out.printf("Average temp = %.1f\n", average);
System.out.println(count + " days above average");
}
}
Arrays.sort(temps);
double median = 0;
if (temps.length % 2 == 1) {median = temps[temps.length/2];}
else {
median = (temps[temps.length/2] + temps[temps.length/2 - 1])/2;
}
System.out.printf(" High Score: %6.2f\n Mean Score: %6.2f\n", temps[temps.length-1], average);
System.out.printf("Median Score: %6.2f\n Low Score: %6.2f\n", median, temps[0]);
Review of Quiz 19
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
50
OUTPUT:
We need only to modify the prompts to get the desired output
Review of Quiz 19
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
51
Complete Program:// Reads test scores and calculates high, low, mean and median
import java.util.*;
public class Quiz19 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many test scores do you wish to enter? ");
int number = console.nextInt();
double[] scores = new double[number]; // array to store scores
double sum = 0;
for (int i = 0; i < number; i++) { // read/store each score
System.out.print("Please enter test " + (i + 1) + "'s score: ");
scores[i] = console.nextDouble();
sum += scores[i];}
double mean = sum / number;
Arrays.sort(scores);
double high = scores[number-1];
double low = scores[0];
double median = 0;
if(number%2 == 0) {
median = (scores[number/2] + scores[number/2 - 1])/2; }
else {
median = scores[number/2]; }
// report results
System.out.printf("Test Statistics:\n");
System.out.printf(" High Score: %6.2f\n", high);
System.out.printf(" Mean Score: %6.2f\n", mean);
System.out.printf(" Median Score: %6.2f\n", median);
System.out.printf(" Low Score: %6.2f\n", low);
}
}
Review of Quiz 19
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
52
Complete Program:// Reads test scores and calculates high, low, mean and median
import java.util.*;
public class Quiz19 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many test scores do you wish to enter? ");
int number = console.nextInt();
double[] scores = new double[number]; // array to store scores
double sum = 0;
for (int i = 0; i < number; i++) { // read/store each score
System.out.print("Please enter test " + (i + 1) + "'s score: ");
scores[i] = console.nextDouble();
sum += scores[i];}
double mean = sum / number;
Arrays.sort(scores);
double high = scores[number-1];
double low = scores[0];
double median = 0;
if(number%2 == 0) {
median = (scores[number/2] + scores[number/2 - 1])/2; }
else {
median = scores[number/2]; }
// report results
System.out.printf("Test Statistics:\n");
System.out.printf(" High Score: %6.2f\n", high);
System.out.printf(" Mean Score: %6.2f\n", mean);
System.out.printf(" Median Score: %6.2f\n", median);
System.out.printf(" Low Score: %6.2f\n", low);
}
}
Review of Quiz 20
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
53
Use Quiz 19 as your model
Only the second part of Quiz 19 needs to be modified
You will print the array in the order it was entered using Arrays.toString
You will the use Arrays.sort to sort the array into ascending order and print it using Arrays.toString
Finally you will use your method to reverse the array and print the array in descending order using Arrays.toString
Review of Quiz 20
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
54
The Program form Quiz 19:import java.util.*;
public class Quiz19 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many test scores do you wish to enter? ");
int number = console.nextInt();
double[] scores = new double[number]; // array to store scores
double sum = 0;
for (int i = 0; i < number; i++) { // read/store each score
System.out.print("Please enter test " + (i + 1) + "'s score: ");
scores[i] = console.nextDouble();
sum += scores[i];}
double mean = sum / number;
Arrays.sort(scores);
double high = scores[number-1];
double low = scores[0];
double median = 0;
if(number%2 == 0) {
median = (scores[number/2] + scores[number/2 - 1])/2; }
else {
median = scores[number/2]; }
// report results
System.out.printf("Test Statistics:\n");
System.out.printf(" High Score: %6.2f\n", high);
System.out.printf(" Mean Score: %6.2f\n", mean);
System.out.printf(" Median Score: %6.2f\n", median);
System.out.printf(" Low Score: %6.2f\n", low);
}
}
System.out.printf("Original array = %s\n", Arrays.toString(scores));
Arrays.sort(scores);
System.out.printf(" Sorted array = %s\n", Arrays.toString(scores));
System.out.printf("Reversed array = %s\n", Arrays.toString(reverse(scores)));
}
//Add your method to reverse the elements of an array
public static double[] reverse(double[] array) {
for (int i = 0; i < array.length/2; i++) {
double temp = array[i];
array[i] = array[array.length - i -1];
array[array.length - i -1] = temp;}
return array;
Replace this
Review of Quiz 20
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
55
Replaced code:
System.out.printf("Original array = %s\n", Arrays.toString(scores));
Arrays.sort(scores);
System.out.printf(" Sorted array = %s\n", Arrays.toString(scores));
System.out.printf("Reversed array = %s\n", Arrays.toString(reverse(scores)));
}
public static double[] reverse(double[] array) {
for (int i = 0; i < array.length/2; i++) {
double temp = array[i];
array[i] = array[array.length - i -1];
array[array.length - i -1] = temp;}
return array;
}
Print original array Sort the array Print sorted array
Print the reversed array
The print statement contains the call to your method reverse that reverses the array
Review of Quiz 20
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
56
Replaced code:
System.out.printf("Original array = %s\n", Arrays.toString(scores));
Arrays.sort(scores);
System.out.printf(" Sorted array = %s\n", Arrays.toString(scores));
System.out.printf("Reversed array = %s\n", Arrays.toString(reverse(scores)));
}
public static double[] reverse(double[] array) {
for (int i = 0; i < array.length/2; i++) {
double temp = array[i];
array[i] = array[array.length - i -1];
array[array.length - i -1] = temp;}
return array;
}
Accepts a double precision array as a parameter
Explicitly returns the reversed array to the main program
NOTE: The array passed by reference as a parameter has already been reversed. The explicit return allows us to use the method in a print statement.
Review of Quiz 20
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
57
OUTPUT:
Printout verifies that the sort and reverse do work properly
Review of Quiz 21
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
58
Use Quiz 20 as your model for the input dialogue
Set up the random numbers as specified in item 2, Quiz 21
The main program will use:int inversions = inversion(array);
To count the inversions.
Next calculate the percent
The main program prints out the array, inversions and percent
Finally, you need to write the method inversion to count the inversions (using Lecture 20 slide 65)
Review of Quiz 21
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
59
The input dialogue:
import java.util.*;
public class Quiz21 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many random integers do you want? ");
int number = console.nextInt();
double[] array = new double[number]; // array to store random numbers
System.out.print("What is the minimum number? ");
int min = console.nextInt();
System.out.print("What is the maximum number? ");
int max = console.nextInt();
int range = max - min +1;
1. Prompt for the size of the array
2. Get size from console andcreate the array
3. Prompt for minimum
4. Get minimum from console 5. Prompt for maximum
6. Get maximum from console 7. Set random numbers
Review of Quiz 21
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
60
Complete the main program:
Random r = new Random();
for (int i = 0; i < number; i++) { // generate random number
array[i] = r.nextInt(range) + min;}
int inversions = inversion(array);
double percent = 200.0*inversions/number/(number-1);
System.out.printf("Original array = %s contains %d inversions
(%.1f%s).\n", Arrays.toString(array), inversions, percent, "%");
}
1. Create random object
2. Fill array with random numbers
3. Calculate inversions
4. Calculate percent
5. Print resultsNOTE: Trick to print out % in printf statement
Review of Quiz 21
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
61
Method inversion():
public static int inversion(double[] data) {
int count = 0;
for (int i = 0; i < data.length - 1; i++) {
for (int j = i + 1; j < data.length; j++) {
if (data[i] > data[j]) {
count++;}
}
}
return count;
}
1. Returns integer (# of inversions)
2. Accepts an array
3. Initialize the inversion count
4. Optimized inversion algorithm
5. Returns inversion count
Review of Quiz 21
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
62
Complete Program:import java.util.*;
public class Quiz21 {public static void main(String[] args) {
Scanner console = new Scanner(System.in);System.out.print("How many random integers do you want? ");int number = console.nextInt();double[] array = new double[number]; // array to store random numbersSystem.out.print("What is the minimum number? ");int min = console.nextInt();System.out.print("What is the maximum number? ");int max = console.nextInt();int range = max - min +1;Random r = new Random();for (int i = 0; i < number; i++) { // generate random number
array[i] = r.nextInt(range) + min;}int inversions = inversion(array);double percent = 200.0*inversions/number/(number-1);System.out.printf("Original array = %s contains %d inversions (%.1f%s).\n", Arrays.toString(array), inversions, percent, "%");
} public static int inversion(double[] data) {
int count = 0;for (int i = 0; i < data.length - 1; i++) {
for (int j = i + 1; j < data.length; j++) {if (data[i] > data[j]) {
count++;}// System.out.println("(" + data[i] + ", " + data[j] + ")");}
}}return count;
}}
This program is suitable for copy and paste to DrJava
Review of Quiz 21
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
63
OUTPUT:
This is the array of random numbers printed out using Arrays.toString()
This is the actual number of inversions in the array This is the percentage of inversions in the array
Review of Quiz 21
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
64
OUTPUT:
If the percent of inversions is 0%, the array is sorted in ascending order
If the percent of inversions is 100%, the array is sorted in descending order
This array is nearly a perfect random array (50% inversions)
With only 10 elements in the array, your results can vary greatly from the ideal 50%
Review of Quiz 22
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
65
Use Quiz 21 as your model for the input dialogue
Ask for number of rows, then setup array with columns blankdouble[][] array = new double[row][];
Review of Quiz 22
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
66
Use Quiz 21 as your model for the input dialogue
Ask for number of rows, then setup array with columns blank
Set up a for loop to enter the number of columns for each row and the column data
double[][] array = new double[row][];
for (int i =0; i < row; i++) {
System.out.printf("Row%3d: Enter number of columns
followed by values: ", i+1);
int col = console.nextInt();
array[i] = new double[col];
for (int j = 0; j < col; j++) {
array[i][j] = console.nextDouble();}
}
Review of Quiz 22
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
67
Use Quiz 21 as your model for the input dialogue
Ask for number of rows, then setup array with columns blank
Set up a for loop to enter the number of columns for each row and the column data
double[][] array = new double[row][];
for (int i =0; i < row; i++) {
System.out.printf("Row%3d: Enter number of columns
followed by values: ", i+1);
int col = console.nextInt();
array[i] = new double[col];
for (int j = 0; j < col; j++) {
array[i][j] = console.nextDouble();}
}
After all data is entered, use the method from page 488 of the text to print out the whole array.
Review of Quiz 22
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
68
Use Quiz 21 as your model for the input dialogue
Ask for number of rows, then setup array with columns blank
Set up a for loop to enter the number of columns for each row and the column data
double[][] array = new double[row][];
After all data is entered, use the method from page 488 of the text to print out the whole array.
public static void print(double[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");}
System.out.println();}
}
Review of Quiz 22
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
69
Use Quiz 21 as your model for the input dialogue
Ask for number of rows, then setup array with columns blank
Set up a for loop to enter the number of columns for each row and the column data
double[][] array = new double[row][];
After all data is entered, use the method from page 488 of the text to print out the whole array.
public static void print(double[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");}
System.out.println();}
}
Review of Quiz 22
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
70
Use Quiz 21 as your model for the input dialogue
Ask for number of rows, then setup array with columns blank
Set up a for loop to enter the number of columns for each row and the column data
double[][] array = new double[row][];
After all data is entered, use the method from page 488 of the text to print out the whole array.
import java.util.*;
public class Quiz22 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many rows do you want? ");
int row = console.nextInt();
double[][] array = new double[row][];
for (int i =0; i < row; i++) {
System.out.printf("Row%3d: Enter number of columns followed by values: ", i+1);
int col = console.nextInt();
array[i] = new double[col];
for (int j = 0; j < col; j++) {
array[i][j] = console.nextDouble();}
}
System.out.println();
print(array);
}
public static void print(double[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");}
System.out.println();}
}
}
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
71
Use Lecture 22 Slide 42 as your starting point
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
72
Use Lecture 22 Slide 42 as your starting point
Replace the System.out.println() statement with:
System.out.println("Deal five cards:");
Add a loop that executes five times with a single printf statement to print the output as shown:
System.out.println(“Deal five cards:“);
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
73
Use Lecture 22 Slide 42 as your starting point
Replace the System.out.println() statement with:
System.out.println("Deal five cards:");
Add a loop that executes five times with a single printf statement to print the output as shown:
System.out.println(“Deal five cards:“);
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n",
i, deck.get(i-1), value(deck.get(i-1)));}
Let’s look at this printf statement in detail
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
74
System.out.println(“Deal five cards:“);
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n",
i, deck.get(i-1), value(deck.get(i-1)));}
Let’s look at this printf statement in detail
import java.util.*;
public class Quiz23 {
public static void main(String[] args) {
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
List<String> deck = new ArrayList<String>();
for (String rank : ranks) { // build sorted deck
for (String suit : suits) {
deck.add(rank + " of " + suit);}}
Collections.shuffle(deck);
System.out.println("Deal five cards:");
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n", i, deck.get(i-1), value(deck.get(i-1)));}
}
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
75
System.out.println(“Deal five cards:“);
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n",
i, deck.get(i-1), value(deck.get(i-1)));}
import java.util.*;
public class Quiz23 {
public static void main(String[] args) {
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
List<String> deck = new ArrayList<String>();
for (String rank : ranks) { // build sorted deck
for (String suit : suits) {
deck.add(rank + " of " + suit);}}
Collections.shuffle(deck);
System.out.println("Deal five cards:");
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n", i, deck.get(i-1), value(deck.get(i-1)));}
}
The %d formats an integer card numberThe %-17s left justifies (-) the String representing the card drawn in 17 character spaces.
Queen of Diamonds is largest and takes 17 characters
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
76
System.out.println(“Deal five cards:“);
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n",
i, deck.get(i-1), value(deck.get(i-1)));}
import java.util.*;
public class Quiz23 {
public static void main(String[] args) {
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
List<String> deck = new ArrayList<String>();
for (String rank : ranks) { // build sorted deck
for (String suit : suits) {
deck.add(rank + " of " + suit);}}
Collections.shuffle(deck);
System.out.println("Deal five cards:");
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n", i, deck.get(i-1), value(deck.get(i-1)));}
}
Finally, we print out the value of the card in integer (%d) format
This uses the method “value” that we must write to return the value of the card
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
77
System.out.println(“Deal five cards:“);
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n",
i, deck.get(i-1), value(deck.get(i-1)));}
import java.util.*;
public class Quiz23 {
public static void main(String[] args) {
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
List<String> deck = new ArrayList<String>();
for (String rank : ranks) { // build sorted deck
for (String suit : suits) {
deck.add(rank + " of " + suit);}}
Collections.shuffle(deck);
System.out.println("Deal five cards:");
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n", i, deck.get(i-1), value(deck.get(i-1)));}
}
Finally, we print out the value of the card in integer (%d) format
This uses the method “value” that we must write to return the value of the card
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
78
System.out.println(“Deal five cards:“);
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n",
i, deck.get(i-1), value(deck.get(i-1)));}
import java.util.*;
public class Quiz23 {
public static void main(String[] args) {
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
List<String> deck = new ArrayList<String>();
for (String rank : ranks) { // build sorted deck
for (String suit : suits) {
deck.add(rank + " of " + suit);}}
Collections.shuffle(deck);
System.out.println("Deal five cards:");
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n", i, deck.get(i-1), value(deck.get(i-1)));}
}
public static int value(String card) {
char number = card.charAt(0);
if (number == '1') {return 10;}
if (number == 'J') {return 10;}
if (number == 'Q') {return 10;}
if (number == 'K') {return 10;}
if (number == 'A') {return 11;}
return Character.getNumericValue(number);}
Grab the first character of the card description
The first character is a 1, J, Q, or K for 10, Jack, Queen or King –each of which has value 10.
The Ace has a value of 11
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
79
System.out.println(“Deal five cards:“);
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n",
i, deck.get(i-1), value(deck.get(i-1)));}
import java.util.*;
public class Quiz23 {
public static void main(String[] args) {
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
List<String> deck = new ArrayList<String>();
for (String rank : ranks) { // build sorted deck
for (String suit : suits) {
deck.add(rank + " of " + suit);}}
Collections.shuffle(deck);
System.out.println("Deal five cards:");
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n", i, deck.get(i-1), value(deck.get(i-1)));}
}
public static int value(String card) {
char number = card.charAt(0);
if (number == '1') {return 10;}
if (number == 'J') {return 10;}
if (number == 'Q') {return 10;}
if (number == 'K') {return 10;}
if (number == 'A') {return 11;}
return Character.getNumericValue(number);}
All other cards start with the value of the card
Use the methodCharacter.getNumericValue()
to convert the character to its integer value equivalent
Review of Quiz 23
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
80
System.out.println(“Deal five cards:“);
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n",
i, deck.get(i-1), value(deck.get(i-1)));}
import java.util.*;
public class Quiz23 {
public static void main(String[] args) {
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
List<String> deck = new ArrayList<String>();
for (String rank : ranks) { // build sorted deck
for (String suit : suits) {
deck.add(rank + " of " + suit);}}
Collections.shuffle(deck);
System.out.println("Deal five cards:");
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n", i, deck.get(i-1), value(deck.get(i-1)));}
}
public static int value(String card) {
char number = card.charAt(0);
if (number == '1') {return 10;}
if (number == 'J') {return 10;}
if (number == 'Q') {return 10;}
if (number == 'K') {return 10;}
if (number == 'A') {return 11;}
return Character.getNumericValue(number);}
Here is the entire program:
import java.util.*;
public class Quiz23 {
public static void main(String[] args) {
String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King",
"Ace"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
List<String> deck = new ArrayList<String>();
for (String rank : ranks) { // build sorted deck
for (String suit : suits) {
deck.add(rank + " of " + suit);}}
Collections.shuffle(deck);
System.out.println("Deal five cards:");
for (int i = 1; i <= 5; i++) {
System.out.printf(" Card %d = %-17s value of card = %d.\n", i, deck.get(i-1),
value(deck.get(i-1)));}
}
public static int value(String card) {
char number = card.charAt(0);
if (number == '1') {return 10;}
if (number == 'J') {return 10;}
if (number == 'Q') {return 10;}
if (number == 'K') {return 10;}
if (number == 'A') {return 11;}
return Character.getNumericValue(number);}
}
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
81
You need to download the GRE vocabulary file from the class web page
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
82
You need to download the GRE vocabulary file from the class web page
The file will be used in Lab 13 –download by clicking here
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
83
You need to download the GRE vocabulary file from the class web page
The file will be used in Lab 13 –download by clicking here
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
84
You need to download the GRE vocabulary file from the class web page
The file will be used in Lab 13 –download by clicking here
Different browsers have different ways of selecting the data. For most browsers, ctrl-a, will select all the data
If this does not work, highlight the first word and then do a shift-left-click on the last word
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
85
You need to download the GRE vocabulary file from the class web page
The file will be used in Lab 13 –download by clicking here
Different browsers have different ways of selecting the data. For most browsers, ctrl-a, will select all the data
If this does not work, highlight the first word and then do a shift-left-click on the last word
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
86
You need to download the GRE vocabulary file from the class web page
After highlighting the text, a right-click on any highlighted word will bring up the copy menu
Copy the data to the clip board
Then paste into notepad or Word and save as a text file (wordLink.txt) in the same directory as your Java programs
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
87
You need to download the GRE vocabulary file from the class web page
After highlighting the text, a right-click on any highlighted word will bring up the copy menu
Copy the data to the clip board
Then paste into notepad or Word and save as a text file (wordLink.txt) in the same directory as your Java programs
Be sure to save the file as wordList.txt in the same directory as your Java files
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
88
Next copy and paste the main program into DrJava
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
89
Next copy and paste the main program into DrJava
import java.io.*; // for File (FILE from Quiz 17)
import java.util.*; // Java utilities
public class Quiz24 {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("wordList.txt");
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns " + f.getAbsolutePath());
int count = 0;
while (input.hasNext()) {
input.next();
count++; }
System.out.println("total words = " + count);
The beginning of this file is from Quiz 17
It checks to be sure the file exists, can be read, finds its length and absolute path and finally counts the number of words in the file
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
90
Next copy and paste the main program into DrJava
import java.io.*; // for File (FILE from Quiz 17)
import java.util.*; // Java utilities
public class Quiz24 {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("wordList.txt");
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns " + f.getAbsolutePath());
int count = 0;
while (input.hasNext()) {
input.next();
count++; }
System.out.println("total words = " + count);
The beginning of this file is from Quiz 17
It checks to be sure the file exists, can be read, finds its length and absolute path and finally counts the number of words in the file
The next part of the file sets up the text file to be read and calls the two methods that we are to write to do the Sequential Search and the Binary Search
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
91
Next copy and paste the main program into DrJava
import java.io.*; // for File (FILE from Quiz 17)
import java.util.*; // Java utilities
public class Quiz24 {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("wordList.txt");
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns " + f.getAbsolutePath());
int count = 0;
while (input.hasNext()) {
input.next();
count++; }
System.out.println("total words = " + count);
The beginning of this file is from Quiz 17
It checks to be sure the file exists, can be read, finds its length and absolute path and finally counts the number of words in the file
The next part of the file sets up the text file to be read and calls the two methods that we are to write to do the Sequential Search and the Binary Search
File wordList = new File("wordList.txt");
String words[] = new String[count];
Scanner wordFile = new Scanner(wordList);
for (int i = 0; i < count; i++) {words[i] = wordFile.nextLine();}
Scanner console = new Scanner(System.in);
System.out.print("Enter a word to search for: ");
String target = console.nextLine();
target = target.toLowerCase();
int indexSequential[] = new int[2];
indexSequential = indexOf(words, target);
int indexBinary[] = new int[2];
indexBinary = binarySearch(words, target);
Name the file wordList and set up Scanner wordFile to read the words from “wordList.txt”Set up the String array word[] to hold the count = 69,900 words in wordList.txt
Read the words from the file to the array word[]
Get the target word from the console and store it in String target
to store the results of the Sequential and Binary Searches Create 2-dimensional arrays
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
92
Next copy and paste the main program into DrJava
import java.io.*; // for File (FILE from Quiz 17)
import java.util.*; // Java utilities
public class Quiz24 {
public static void main(String[] args) thr ows FileNotFoundException {
File f = new File("wordList.txt");
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns " + f.getAbsolutePath());
int count = 0;
while (input.hasNext()) {
input.next();
count++; }
System.out.println("total words = " + count);
The beginning of this file is from Quiz 17
It checks to be sure the file exists, can be read, finds its length and absolute path and finally counts the number of words in the file
The next part of the file sets up the text file to be read and calls the two methods that we are to write to do the Sequential Search and the Binary Search
File wordList = new File("wordList.txt");
String words[] = new String[count];
Scanner wordFile = new Scanner(wordList);
for (int i = 0; i < count; i++) {words[i] = wordFile.nextLine();}
Scanner console = new Scanner(System.in);
System.out.print("Enter a word to search for: ");
String target = console.nextLine();
target = target.toLowerCase();
int indexSequential[] = new int[2];
indexSequential = indexOf(words, target);
int indexBinary[] = new int[2];
indexBinary = binarySearch(words, target);
Name the file wordList and set up Scanner wordFile to read the words from “wordList.txt”Set up the String array word[] to hold the count = 69,900 words in wordList.txt
Read the words from the file to the array word[]
Get the target word from the console and store it in String target
to store the results of the Sequential and Binary Searches Create 2-dimensional arrays
The final part of the main program checks to see if the target was found. The print statements are different for target found and target not found
if(indexBinary[0] >= 0) {
System.out.printf("\nUsing Sequential Search, target %s found at %d in %d iterations.\n"
, target, indexSequential[0], indexSequential[1]);
System.out.printf("Using Binary Search, target %s found at %d in %d iterations.\n"
, target, indexBinary[0], indexBinary[1]);}
else {
System.out.printf("\nUsing Sequential Search, target %s was NOT found in %d iterations.\n"
, target, indexSequential[1]);
System.out.printf("Using Binary Search, target %s was NOT found in %d iterations.\n"
, target, indexBinary[1]);}
}
Printed when target is NOT found
Printed when target is found
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
93
Next copy and paste the main program into DrJava
import java.io.*; // for File (FILE from Quiz 17)
import java.util.*; // Java utilities
public class Quiz24 {
public static void main(String[] args) thr ows FileNotFoundException {
File f = new File("wordList.txt");
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns " + f.getAbsolutePath());
int count = 0;
while (input.hasNext()) {
input.next();
count++; }
System.out.println("total words = " + count);
The beginning of this file is from Quiz 17
It checks to be sure the file exists, can be read, finds its length and absolute path and finally counts the number of words in the file
The next part of the file sets up the text file to be read and calls the two methods that we are to write to do the Sequential Search and the Binary Search
File wordList = new File("wordList.txt");
String words[] = new String[count];
Scanner wordFile = new Scanner(wordList);
for (int i = 0; i < count; i++) {words[i] = wordFile.nextLine();}
Scanner console = new Scanner(System.in);
System.out.print("Enter a word to search for: ");
String target = console.nextLine();
target = target.toLowerCase();
int indexSequential[] = new int[2];
indexSequential = indexOf(words, target);
int indexBinary[] = new int[2];
indexBinary = binarySearch(words, target);
Name the file wordList and set up Scanner wordFile to read the words from “wordList.txt”Set up the String array word[] to hold the count = 69,900 words in wordList.txt
Read the words from the file to the array word[]
Get the target word from the console and store it in String target
to store the results of the Sequential and Binary Searches Create 2-dimensional arrays
The final part of the main program checks to see if the target was found. The print statements are different for target found and target not found
if(indexBinary[0] >= 0) {
System.out.printf("\nUsing Sequential Search, target %s found at %d in %d iterations.\n"
, target, indexSequential[0], indexSequential[1]);
System.out.printf("Using Binary Search, target %s found at %d in %d iterations.\n"
, target, indexBinary[0], indexBinary[1]);}
else {
System.out.printf("\nUsing Sequential Search, target %s was NOT found in %d iterations.\n"
, target, indexSequential[1]);
System.out.printf("Using Binary Search, target %s was NOT found in %d iterations.\n"
, target, indexBinary[1]);}
}
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
94
Next we need to write the two search methods: Sequential Search and Binary Search
These need to be changed to Strings
These need to be changed to an integer array of size 2:int[] temp = new int[2];
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
95
Next we need to write the two search methods: Sequential Search and Binary Search
// Sequential Search p. 846 of text
public static int[] indexOf(String[] strings,
String target) {
int[] temp = new int[2];
int iterations = 0;
for (int i = 0; i < strings.length; i++) {
iterations++;
if (strings[i].equals(target)) {
temp[0] = i;
temp[1] = iterations;
return temp;}} // found it!
temp[0] = -1;
temp[1] = iterations;
return temp; // not found
}
Strings
Change the return to an integer array size 2
Sequential Algorithm
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
96
Next we need to write the two search methods: Sequential Search and Binary Search
// Sequential Search p. 846 of text
public static int[] indexOf(String[] strings,
String target) {
int[] temp = new int[2];
int iterations = 0;
for (int i = 0; i < strings.length; i++) {
iterations++;
if (strings[i].equals(target)) {
temp[0] = i;
temp[1] = iterations;
return temp;}} // found it!
temp[0] = -1;
temp[1] = iterations;
return temp; // not found
}
Keep track of iterations
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
97
Next we need to write the two search methods: Sequential Search and Binary Search
Change the return to an integer array of size 2
We need to add code to keep track of the number of iterations
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
98
Next we need to write the two search methods: Sequential Search and Binary Search
Change the return to an integer array of size 2
We need to add code to keep track of the number of iterations
public static int[] binarySearch(String[] strings, String target) {
int[] temp = new int[2];
int iterations = 0;
int min = 0;
int max = strings.length - 1;
while (min <= max) {
iterations++;
int mid = (max + min) / 2;
int compare = strings[mid].compareTo(target);
if (compare == 0) {
temp[0] = mid;
temp[1] = iterations;
return temp;} // found it!
else if (compare < 0) {
min = mid + 1;} // too small
else { // compare > 0
max = mid - 1;} // too large
}
temp[0] = -1;
temp[1] = iterations;
return temp; // not found
}
Change the return to an array of size 2
Count the iterations
Review of Quiz 24
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
99
Next we need to write the two search methods: Sequential Search and Binary Search
Change the return to an integer array of size 2
We need to add code to keep track of the number of iterations
public static int[] binarySearch(String[] strings, String target) {
int[] temp = new int[2];
int iterations = 0;
int min = 0;
int max = strings.length - 1;
while (min <= max) {
iterations++;
int mid = (max + min) / 2;
int compare = strings[mid].compareTo(target);
if (compare == 0) {
temp[0] = mid;
temp[1] = iterations;
return temp;} // found it!
else if (compare < 0) {
min = mid + 1;} // too small
else { // compare > 0
max = mid - 1;} // too large
}
temp[0] = -1;
temp[1] = iterations;
return temp; // not found
}
Change the return to an array of size 2
Count the iterations
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
100
For lapin the Binary Search take only ONE iteration
For Yoga the Binary Search has fewer iterations
For Michael the Binary Search has fewer iterations
For aback the Sequential Search has fewer iterations
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
101
import java.io.*; // for File (FILE from Quiz 17)
import java.util.*; // Java utilities
public class Quiz24 {
public static void main(String[] args) throws FileNotFoundException {
File f = new File("wordList.txt");
Scanner input = new Scanner(f);
System.out.println("exists returns " + f.exists());
System.out.println("canRead returns " + f.canRead());
System.out.println("length returns " + f.length());
System.out.println("getAbsolutePath returns " + f.getAbsolutePath());
First third of the main program
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
102
int count = 0;
while (input.hasNext()) {
input.next();
count++; }
System.out.println("total words = " + count);
File wordList = new File("wordList.txt");
String words[] = new String[count];
Scanner wordFile = new Scanner(wordList);
for (int i = 0; i < count; i++) {words[i] = wordFile.nextLine();}
Scanner console = new Scanner(System.in);
System.out.print("Enter a word to search for: ");
String target = console.nextLine();
target = target.toLowerCase();
int indexSequential[] = new int[2];
indexSequential = indexOf(words, target);
int indexBinary[] = new int[2];
indexBinary = binarySearch(words, target);
Second third of the main program
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
103
if(indexBinary[0] >= 0) {
System.out.printf("\nUsing Sequential Search, target %s found at %d in
%d iterations.\n"
, target, indexSequential[0], indexSequential[1]);
System.out.printf("Using Binary Search, target %s found at %d in %d
iterations.\n"
, target, indexBinary[0], indexBinary[1]);}
else {
System.out.printf("\nUsing Sequential Search, target %s was NOT found
in %d iterations.\n"
, target, indexSequential[1]);
System.out.printf("Using Binary Search, target %s was NOT found in %d
iterations.\n"
, target, indexBinary[1]);}
}
Last third of the main program
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
104
// Sequential Search p. 846 of text
public static int[] indexOf(String[] strings,
String target) {
int[] temp = new int[2];
int iterations = 0;
for (int i = 0; i < strings.length; i++) {
iterations++;
if (strings[i].equals(target)) {
temp[0] = i;
temp[1] = iterations;
return temp;}} // found it!
temp[0] = -1;
temp[1] = iterations;
return temp; // not found
}
Sequential Search Method
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
105
public static int[] binarySearch(String[] strings, String target) {
int[] temp = new int[2];
int iterations = 0;
int min = 0;
int max = strings.length - 1;
while (min <= max) {
iterations++;
int mid = (max + min) / 2;
int compare = strings[mid].compareTo(target);
if (compare == 0) {
temp[0] = mid;
temp[1] = iterations;
return temp;} // found it!
else if (compare < 0) {
min = mid + 1;} // too small
else { // compare > 0
max = mid - 1;} // too large
}
temp[0] = -1;
temp[1] = iterations;
return temp; // not found
}
}
Binary Search Method
Review of Quiz 25
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
106
You are to write method recursive to print words from the file wordList.txt in forward and then reverse order
You will be using the file wordList.txt from the web page
The main program has been written for you
• Sets up text file• Asks user how many
iterations• Calls recursive
Review of Quiz 25
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
107
We need to write the method recursive
The recursive base (n <= 0) will print out “Reverse:”
On the way up, the method prints the words from wordList.txt in reverse order
On the way down, the method prints the words from wordList.txt in forward order
Review of Quiz 25
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
108
We need to write the method recursive
The recursive base (n <= 0) will print out “Reverse:”
On the way up, the method prints the words from wordList.txt in reverse order
On the way down, the method prints the words from wordList.txt in forward order
Review of Quiz 25
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
109
public static void recursive(Scanner input, int n) {
if (n <= 0) {System.out.printf("\n\nReverse:\n");}
else {
String temp = input.nextLine();
System.out.printf("\n%s ", temp);
recursive(input, n-1);
System.out.printf("\n%s ", temp);}
}
The base (n <= 0) prints out “Reverse:”
On the way down, read the next word from wordList.txt and print it out (forward order)
On the way up, just print the word out (reverse order)
Review of Quiz 25
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
110
public static void recursive(Scanner input, int n) {
if (n <= 0) {System.out.printf("\n\nReverse:\n");}
else {
String temp = input.nextLine();
System.out.printf("\n%s ", temp);
recursive(input, n-1);
System.out.printf("\n%s ", temp);}
}
The base (n <= 0) prints out “Reverse:”
On the way up, just print the word out (reverse order)
On the way down, read the next word from wordList.txt and print it out (forward order)On the way down, read
the next word from wordList.txt and print it out (forward order)
The base (n <= 0) prints out “Reverse:”
On the way up, just print the word out (reverse order)
Review of Quiz 25
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
111
public static void recursive(Scanner input, int n) {
if (n <= 0) {System.out.printf("\n\nReverse:\n");}
else {
String temp = input.nextLine();
System.out.printf("\n%s ", temp);
recursive(input, n-1);
System.out.printf("\n%s ", temp);}
}
The base (n <= 0) prints out “Reverse:”
On the way up, just print the word out (reverse order)
On the way down, read the next word from wordList.txt and print it out (forward order)
import java.util.*;
import java.io.*;
public class Quiz25 {
public static void main(String[] args) throws
FileNotFoundException {
File f = new File("wordList.txt");
Scanner input = new Scanner(f);
Scanner console = new Scanner(System.in);
System.out.print("Enter number of recursions: ");
int n = console.nextInt();
recursive(input, n);
System.out.println();
}
public static void recursive(Scanner input, int n) {
if (n <= 0) {System.out.printf("\n\nReverse:\n");}
else {
String temp = input.nextLine();
System.out.printf("\n%s ", temp);
recursive(input, n-1);
System.out.printf("\n%s ", temp);}
}
}
Assignments for this week1. Laboratory for Chapter 12 due Today (Monday 12/1)
• IMPORTANT: When you email me your laboratory Word Document, be sure it is all in one file
2. All lab regrades must be submitted no later than midnight Monday 12/15/2014.
3. FINAL EXAM in this room, next Wednesday (12/17/2014)
4. Be sure to complete Quiz 26 before leaving class tonight• This is another program to write• You must demonstrate the program to me before you leave lab
COSC 236 :Prof. M.A. Soderstrand Lecture 26 12/01//2014
112