Artificial Intelligence

Total Page:16

File Type:pdf, Size:1020Kb

Artificial Intelligence

AI

Introduction to Artificial Intelligence Unit One – Searching: Depth First vs Breadth First

September 2007

Developed by Shane Torbert with help from Randy Latimer under the direction of Jerry Berry Thomas Jefferson High School for Science and Technology Fairfax County Public Schools, Fairfax, Virginia Java Unit4

Copyright Information

These materials are copyright © 2007 by the author; additional contributions from Randy Latimer. All rights not explicitly granted below are reserved.

You are encouraged to reproduce these materials in whole or in part for use within your educational institution provided appropriate credit is given. You may distribute these materials to other institutions or representatives thereof only if the entire work is transferred in its complete, unaltered form, either as the original Microsoft Word files or as an original, high quality printout.

Ruby version 1.8.6 can be found at http://www.ruby-lang.org/en/ Downloads for Ruby are at http://www.ruby-lang.org/en/downloads/ The Vim editor can be found at http://www.vim.org/download.php. Free FCPS AI course content, with software and materials, is available.

You may alter these materials to suit your needs and distribute these altered materials within your educational institution provided that appropriate credit is given and that the nature of your changes is clearly indicated. You may not distribute altered versions of these materials to any other institution.

If you have any questions about this agreement please e-mail [email protected].

Four-2 Java Unit4 AI Instruction Plan—Unit One

Section One – Introduction to Ruby, Generating Neighbors Page Lab00: Introduction to Ruby, ladder_intro.rb ...... One-4 to 13 Lab01: Generating Neighbors, ladder_random.rb...... One-14 to

Section Two – Depth First Search DFS Lab02: Recursive DFS, ladder_dfs.rb...... Four- __to __ Lab03: Iterative Deepening, ladder_dfsid.rb...... Four- __ to __

Section Three – Breadth First Search Lab04: Queue-based Breadth First Search, ladder_bfs.rb...... Four- __ to __

Four-3 Java Unit4 Discussion Solving problems by searching: Simple Search (see Norvig text, Ch. 3)

A problem can be defined by four components:

Initial state: A state that the agent starts in. For example, I'm in Arad trying to get to Bucharest.

Successor function: Given a particular state x, In(Arad), a successor function returns a set of ordered pairs, where each action is legal in state x and each successor is a state that is reached by applying the action. Example, the successor function for the state In(Arad) generates the states In(Timisoara), In(Sibiu), In(Zerind). This initial state and successor function define the state space, the set of all states reachable from the initial state. A path in the state space is a sequence of states connected by a sequence of actions.

Goal test: A condition determining whether a particular state is a goal state. For example, traveling from Arad to Bucharest, the goal state is In(Bucharest).

Path cost: A funtion that assigns a numeric cost to a path. The path costs in the Roumanian map below are the distances between cities. The path cost for traveling from Arad to Bucharest could be the total distance for the particular route taken.

Simple search can be defined as follows: Given: Initial state Successor(state) = {,….} Goal(state) = true or false Find Path from initial state to a goal state

Four-4 Java Unit4

Example problems (see Norvig Ch. 3)

Toy problems

Vacuum world States: The agent is in one of two locations, 2 cells, each cell may or may not contain dirt and may or may not contain the agent (4 possible states for each cell). For 2 cells there are 2 x 2^2 = 8 possible states. Initial state: Any state can be an initial state. Successor function: Generates the legal states that result from trying the three actions (Left – move left, Right – move right, and Suck – pick up dirt). Goal test: are all the squares (the two initial cells) clean.

8-puzzle States: Specify the location of each of the eight tiles and the blank tile in one of the nine squares. Initial state: Any state can be an initial state. Successor function: Generates the legal states that result from trying the four actions (blank moving Left, Right, Up, Down). Goal test: Does the particular state match the goal configuration. Path cost: could be the number of steps in the path to reach the goal.

8-queens States: Any arrangement of 0 to 8 queens on the board. Initial state: No queens on the board. Successor function: Add a queen to an empty square. Goal test: 8 queens on the board, none attacked.

Word ladder States: A dictionary of words. Initial state: Any one word from the dictionary. Successor function: Generate another word, also contained in the dictionary, by changing only one letter, keeping the length of the word the same, and not repeating a word already used - (Change-One-Letter) Goal test: Is the new word generated the same as the goal word (some word also in the dictionary, but different from the initial word).

Four-5 Java Unit4 Lab00 Word Ladder pt. 1

Objective Introduction to Ruby programming and the initial word ladder programming problem.

Background Information on Ruby is available at http://www.ruby-lang.org/en/. Also see Programming Ruby, The Pragmatic Programmer's Guide, http://phrogz.net/ProgrammingRuby/ , or here: http://www.ruby-doc.org/docs/ProgrammingRuby/ , Try Ruby, http://tryruby.hobix.com/ .

Specification Filename ladder_shell.rb. Enter the source code shown below, then run with ruby ladder_shell.rb. Complete the program so that only valid next words are allowed. A next word is valid if it changes only one letter, is in the dictionary, and has not already been used.

1: # Torbert, 8.22.2007 2: 3: $words = File.read(“words.txt”).chomp.split 4: 5: puts 6: while true 7: print “What word to start with? “ 8: current = gets.chomp 9: break if $words.include? current 10: end 11: 12: ladder = Array.new 13: ladder << current 14: for k in 1..5 do 15: puts 16: puts “Current Ladder: #{ladder.inspect}” 17: print “Next word? “ 18: current = gets.chomp 19: ladder << current 20: end 21: 22: puts 23: puts “Ladder:” 24: for k in 1..5 do 25: puts “#{k+1}. #{ladder[k]}” 26: end 27: puts 28: 29: outfile = File.open(“puzzle.txt”, “w”) 30: outfile.puts ladder[0] 31: outfile.puts ladder[-1] 32: outfile.close

Four-6 Java Unit4

Line 3: $words is a global variable (begins with $). Ruby reads the entire text file of words with only one line of code. The class is File, and read is a method from this class. chomp and split store the words from the file into an array. $words is the name of this array.

Line 5: puts is “put string”. With no string to write, this is printing a blank line.

Lines 6-10: A while loop in Ruby. Parentheses for the loop test are optional. The loop needs the end.

Line 8: gets is “get string” from the keyboard. chomp removes the end-of-line marker from the enter key. The word typed is stored in the variable current. Line 9: include? is a method in class Array that returns true/false – boolean - if the argument – current - is in the array object $words. Parentheses for the argument are optional - $words.include?(current) is also okay to use.

Line 12: Creating a new array object called ladder. Another way to do this is: ladder = [] Note that in Ruby the size and type of the the array are not predetermined.

Line 13: Adding an element – current – into the array ladder. This is an array of strings – words.

Lines 14-20: A for loop in Ruby. The range 1..5 is inclusive. With 3 dots the second value is not included: 1...6 would be the numbers 1 through 5. Line 16: With #{ } the value of the ladder array is inserted into the string for puts, and the current ladder array is printed each iteration of the loop.

Lines 17-19: Another word is read in from the keyboard, stripped of the end-of-line character, and stored at the end of the array.

Lines 23-26: Printing the contents of the ladder array using a for loop. The indexes are 0 through 5 – six elements or words in the array.

Line 25: #{ } values are inserted into the print string. The index+1 and the corresponding array value for index are printed, one per line. puts adds an end-of-line.

Lines 29-31: Using class File and the open method to open a new file to write to. Using outfile.puts writes to this file. ladder[0] is the first element, and ladder[-1] is the last element of the array.

Line 32: Close the file in order to save the results of lines 29-31. This program is run through a terminal window. Open two terminal windows, one to edit the file and the other to run the file. To run a Ruby file, use ruby filename.rb.

Save your Ruby file each time you make changes before running.

Test Data Go to www.tjhsst.edu/compsci/ai

Four-7 Java Unit4 Discussion Using terminals to edit and run your program

Normally use two terminals when developing your programs. In one terminal run an editor such as vim. Use the other terminal to run your program. This allows you to make re-edits and re-runs simply.

Sample screenshot of vim editor with a portion of the program file for ladder_shell.rb:

Sample screenshot of running your program in another terminal window:

(to run this program use: ruby ladder_shell.rb)

Four-8 Java Unit4

For debugging, use another terminal to step through your program with interactive ruby: irb

You can enter single lines of ruby code and evaluate these separate lines interactively with the program irb.

Sample screenshot of using irb. Ruby evaluates each line of code you enter, as you type in the code.

Exit irb with the command exit:

Four-9 Java Unit4 Exercises Lab00, experimenting with Ruby

Use irb to evaluate/run these lines of code – or enter the lines in a file such as test.rb and run with ruby test.rb from a terminal (These exercises are from Learning Ruby by M. Fitzgerald, O'Reilly press)

1) puts “Hello “ + “World!” puts “Hello “ << “World!” puts “Hello world” * 5

5.times {print “Hello world”} puts “Hello” * 3 + “ World”

hi = “Hello world” puts hi

hi = “Hello “ who = “World” puts hi + who

puts “Hello #{who}”

puts “Hello, #{ARGV[0]}” This one's special – grabs the first argument off the command line: ruby test.txt World

Formatting a string:

hi = “Hello %s” puts hi % “world” puts hi % “people” puts hi % “universe”

%s, %s % [“Hello”, “World”]

sprintf(“Hello, %s”, “World”) - formats a string

2) Getting input from the terminal.

print “Who do you want to say hello to? “ hello = gets puts “Hello “ + hello

3) Methods – define your own methods using def/end def hello puts “Hello world” end

hello # => Hello world

Four-10 Java Unit4

def repeat (word, times) puts word * times end

5) Classes class Hello def initialize(name) @name = name # @name is an instance variable end

def say_hello puts “Hello “ + @name + “!” end end

hi = Hello.new( “World”) hi.say_hello # => “Hello World!”

4) Using the each method to print all the elements in an array.

[“Hello “, “world”].each {|e| print e}

blocks:

mid_atlantic = [ “Maryland”, “Virginia”, “North Carolina”] mid_atlantic.each do | element | puts element end

same as: mid_atlantic.each { | element | puts element }

5) GUI programming with the Tk toolkit. (see http://www.tcl.tk)

require 'tk' hello = TkRoot.new

TkLabel.new(hello) do

text "\n Hello World! \n"

pack

end

Tk.mainloop

Four-11 Java Unit4

6) Conditionals: if/end if/else/end if/elsif/.../else/end

if a == 10 && b == 27 && c == 43 && d == -14 print sum = a + b + c + d end

7) Type conversions: 13.to_s, “123”.to_i, 97.to_c

8) Loops i = 0 notes = [ “quarter”, “half”, “whole”, “sixteenth”, “rest”] puts notes.size # or notes.length temp = []

while i < notes.size do # the do is optional temp << notes[i].capitalize i += 1 end

temp.sort! notes.replace(temp) p notes # => [“half”, “quarter”, “rest”, “sixteenth”, “whole”]

temp = 98.3 begin print “Your temperature is “ + temp.to_s + “ degrees” temp += 0.1 end while temp < 98.6

Using break

while i < notes.size temp << notes[i].capitalize break if temp[i] = “quarter” i += 1 end

Unless and Until

unless land == “de” dog = “dog” else dog = “Hund” end

weight = 150 until weight == 200 do puts “Weight: “ + weight.to_s weight += 5 end

Four-12 Java Unit4

weight = 150 begin puts “Weight: “ + weight.to_s weight += 5 end until weight == 200 loop

loop do print “Type something: “ line = gets break if line =~ /q|Q/ puts line end for for i in 1..12 print “2 X “ + i.to_s + “ = “, i * 2, “\n” end

for i in 1..12 for j in 1..12 print i_to_s + “ X “ + j.to_s + “ = “, j * i, “\n” end end times and upto

10.times { |i| print i, “ “}

1.upto(10) {|i| print i, “ “}

1.upto(12) {|i| print “2 X “ + i.to_s + “ = “, i * 2, “\n”}

1.upto(12) {|i| 1.upto(12) {|j| print i.to_s + “X” + j.to_s + “ = “, j * i, “\n”}} downto

5.downto(1) {|i| print i, “ “ }

def timer(start) puts “Minutes: “ + start.to_s start_time = Time.now puts start_time.strftime(“Start to_time: %I:%M:%S %p”) start.downto(1) {|i| sleep 60} end_time = Time.now print end_time.strftime(“Elapsed time: %I:%M:%S %p”) end

Four-13 Java Unit4

Arrays months = Array.new months.empty? => true months = Array.new (12) or Array 12 (no parens are necessary for the argument) months.size => 12 months.length => 12

puts months.inspect => prints the values looking like an array or p months

[nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

month = Array.new(12, “month”)

["month", "month", "month", "month", "month", "month", "month", "month", "month", "month", "month", "month"]

month.clear => [] month.empty? => true

num = Array.new(10) { |e| e = e * 2} => [0,2,4,6,8,10,12,14,16,18]

month_abbrv = Array[“jan”, “feb”, “mar”, “apr”] or month_abbrv = [“jan”, “feb”, “mar”, “apr”]

digits = Array(0..9) => [1,2,3, etc ]

months = %w[January February March April etc] => [“January”, “February”, “March”, etc]

months[0] => “January” etc

months.at(0) => “January

months[-1] => last element in the array months[-2] => second to last, etc

or months.first months.last months.first 2

months.index “March” => 2 months[0,3] => months 0 , 1, 2 months[0..3] months[0...3] Two dots – include last index, Three dots – don't include

months.slice(0..2) months.slice(0...2) Four-14 Java Unit4

months.include?(“January”) => true

Concatenation

q1= %w[ January February March ] q2 =%w[ April May June ] q3=%w[ July August September ] q4=%w[ October November December ]

half1 = q1 + q2 half2 = q3 + q4 yr = half1 + half2

<< also concatenates

yrs = [1999] yrs << 2000 => [1999, 2000]

yrs << 2001 << 2002 << 2003 => [1999, 2000, 2001, 2002, 2003]

last_part = q3.concat(q4)

Set operations & intersection - difference | union

uniq! removes duplicates

Stacks and Queues .pop .push operate on the end of the array

.shift .unshift operate on the front of the array

Deleting elements months.delete(“january”) months.delete_at(11)

Arrays and Blocks months.each {|e| print e.capitalize + “ “} month.map {|e| e.capitalize + “ 2007” } => returns an array [“Jan 2007”, “Feb 2007”, etc]

Four-15 Java Unit4 Uninformed search strategies

Basic search algorithm Keep variable successors of unexplored states Initialize with the initial state Pop state off fringe If it’s a goal state, we’re done Else generate all its successor states and put them in successors. [how?] Repeat

Depth first search (stack data structure) Expand from the top of the stack – the deepest unexpanded node. Place successor nodes on the top of the stack. These nodes are also the first to be removed. Breadth first search (queue data structure) Expand from the front of the stack – the deepest unexpanded node. Place successor nodes at the end of the queue (not the front, as in a stack) The next nodes expanded are on the front of the queue. Iterative deepening Depth first search to a fixed depth. If no solution is found, this depth is increased and depth first search is begun again. Initially set the depth to 1. If no solution, perform depth first search to a depth of 2. If no solution, perform the depth first search to a depth of 3, etc.

Four-16 Java Unit4

(image is from http://www.comp.lancs.ac.uk/computing/research/aai- aied/people/paulb/old243prolog/section3_6.html

Depth first search – expand the deepest unexpanded node.

Example: Place the initial node A on the stack. Remove node A and expand to find A's neighbors. Put these on the stack. Remove node B and expand to find B's neighbors (E and F). Put these on the stack. Remove node E and expand to find E's neighbors (J,K and L). Put these on the stack. Remove node J and expand – no new neighbors. Remove node K and expand to find K's neighbors (S, T, and N). Put these on the stack. Remove nodes S, T, and N in turn, no new neighbors. Remove node L. STOP because this is the goal node.

Four-17 Java Unit4 Breadth first search -expand the shallowest unexpanded node.

Example from above, using breadth first search.

Place initial node A on the queue. Remove node A and expand to (B, C, and D). Place these on the queue. Remove node B and expand to (E and F). Put these on the queue. Remove node C and expand – No neighbors. Remove node D and expand to (G, H, and I). Place these on the queue. Remove node E and expand to (J, K, and L). Place these on the queue. Remove node F and expand to (M and N). Place on the queue. Remove node G, no neighbors. Remove node H and place neighbors O, P, and Q on the queue. Remove node I and place neighbor R on the queue. Remove node J – no neighbors. Remove node K, place neighbors S, T, U on the queue. Remove node L and STOP. This is the goal node.

[A] [B C D] [C D E F] [E F G H I] [F G H I J K L] [G H I J K L M N] [I J K L M N O P Q] [J K L M N O P Q R] [L M N O P Q R S T U]

Four-18 Java Unit4 Lab01 Sum, Avg, Min, Max

Objective Processing data in an array.

Background In Driver00 and in Driver01 we declared a constant:

public static final int NUMITEMS = 10;

As a matter of convention, constant values are written in ALLCAPS, tagged as "static final" and placed so that their scope is the scope of the whole driver class. The ALLCAPS makes it easier for us to quickly read our own code. The "static" tag makes these constant values accessible in both static and non-static methods (in both class and instance methods). The "final" tag means that this value cannot be changed. A subsequent command such as NUMITEMS = 15 would be illegal because of the final tag. The class scope makes these constants visible from any method.

Once a Java array is created, we cannot change its length.

Arrays in Java "know" their own length. We can use the public variable array.length to return the length of the array. All the for-loops in the previous labs could have been written using array.length instead of NUMITEMS:

for(int k=0; k < array.length; k++) System.out.println(array[k]);

Be careful! The length variable is a variable not a method. We do not use parentheses on a variable.

When you process an array, you typically want to do something to each cell of the array. As you have seen, a for- loop and an index number is typically used for this purpose. For example, to find the sum of the cells in the array, you would want to visit each cell and add it to the sum. To find the minimum, you would want to visit each cell and compare it to the old minimum. The same algorithm would work for the maximum.

array 3.0 1.2 … 4.5 [0] [1] … [9]

You should organize your code in three separate tasks: fill the array, process the data, and print the results.

Specification Filename Unit4\Lab01\Driver01.java. You may save Driver00.java as Driver01.java Sum: 55.0 and modify the file. Input ten decimal values from the keyboard. Process the array to find the sum of the data. Then calculate the average of the data. Then process the Avg: 5.5 array to find the smallest value and the largest value. Display these four results to Min: 1.0 standard output using System.out. Max: 10.0

Test Data Go to www.tjhsst.edu/compsci.

Four-19 Java Unit4 Exercises Lab01

Answer these questions. 1) public static final int NUMITEMS = 100; double[] array = new double(NUMITEMS);

Explain exactly what the two declarations above accomplish. Draw a picture of the array. Include indexes.

2) Write the code to visit each cell in the array above, and fill it with random doubles between -50 and 50.

3) Write the code to traverse the array, and find the smallest number in the array above.

4) Write the code that searches the array and counts the number of negative numbers.

5) Write the code to calculate the sum of all the numbers in the array above.

6) Use the result from #5 to calculate the average of the numbers in the array.

7) Traverse the array above, calculating the sum of the negative numbers and the sum of the positive numbers.

Four-20 Java Unit4 Lab02 Fahrenheit to Celsius

Objective Arrays, input and output, numeric calculations, decimal formatting.

Background 5 The mathematical formula to convert from Fahrenheit to Celsius is C  (F – 32). 9

In Unit 3, Lab03, we talked about some properties of integer and modulus division. The example there was 37/8 and 37%8. In the formula above, Java sees that 5 and 9 are both integers and therefore does integer division. What is 5/9 ? ______. You will have to find a way to force your Java code to do decimal division, so that 5/9 evaluates to 0.555555556.

You will also have to generate random numbers from 0.0 to 999.9 each showing exactly one decimal place. Recall that Math.random() returns a decimal number between 0 and 1. Somehow, you will have to multiply that decimal so that it falls between 0.0 and 999.9. That decimal still has too many decimal places. You will have to transform the numbers 0.0000000 to 999.999999 into the numbers 0.0 to 999.9. For more help, see page Four-24.

The "\t" escape sequence inserts a tab. This is helpful in displaying text-based tables.

You should organize your code in three separate tasks: fill the array, process the data, and print the table.

Specification Filename Unit4\Lab02\Driver02.java (load). Create two arrays of 15 cells, one for Fahrenheit temperatures and one for Celsius temperatures. Use JOptionPane to read ten of the Fahrenheit temperatures from the user. Generate the last five Fahrenheit temperatures randomly from 0.0 to 999.9 (as described above). Convert all the Fahrenheit temperatures to Celsius. Then display all the values arranged in two columns. Label the columns.

Test Data Go to www.tjhsst.edu/compsci. Fahrenheit | Celsius Extension ------|------Express the Celsius values to one decimal place. 212.0 | 100.0 32.0 | 0.0 1.0 | -17.22222222222222 2.0 | -16.666666666666668 input from the user 3.0 | -16.11111111111111 4.0 | -15.555555555555555 5.0 | -15.0 6.0 | -14.444444444444445 7.0 | -13.88888888888889 8.0 | -13.333333333333334 278.8 | 137.11111111111111 451.9 | 233.27777777777777 generated randomly 936.8 | 502.6666666666667 116.3 | 46.833333333333336 156.8 | 69.33333333333333 Ï

Four-21 Java Unit4 Exercises Lab02

1) What will be the output produced by the following code? int[] a = new int[10]; for (int i = 0; i < a.length; i++) a[i] = 2 * i; for (int i = 0; i < a.length; i++) System.out.print(a[i]) + " ");

2) What will be the output produced by the following code? char[] vowels = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}; for (int index = 0; index < vowels.length; index++) System.out.println(vowels[index]);

3) Given the following declaration: double [] apple = {12.2, -7.3, 14.2, 11.3}; write the code to print each number, its half, and its double.

4) Given the following declaration: double [] banana = {12.2, -7.3, 14.2, 11.3}; write the code to find the average of the array. Then output the numbers in the array as well as how much each number differs from the average.

5) Write the code to fill an array with 20 values of the type double, read in from the keyboard.

Four-22 Java Unit4 Discussion Reading Text Files

In Labs00 and 01, you entered data from the keyboard. The Java class you used was JOptionPane and the method was showInputDialog(). This works fine for entering small amounts of data. However, entering large amounts of data from the keyboard is not convenient. For large data sets it is better to read from a text file. That is, the data comes from a file previously stored on your hard drive. Here is Driver00, re-written to read the data from a text file. You should compare and contrast this code with the code on page Four-4. The new commands relating to text files are in bold.

1 import java.io.*; 2 import java.util.*; 3 public class Driver00 4 { 5 public static final int NUMITEMS = 10; 6 public static void main(String[] args) throws Exception 7 { 8 Scanner infile = new Scanner( new File("filename.txt") ); 9 double[] array = new double[NUMITEMS]; 10 for(int x = 0; x < NUMITEMS; x++) 11 array[x] = infile.nextDouble(); 12 infile.close(); 13 System.out.println("The numbers in the file, backwards:"); 14 for(int x = 0; x < NUMTIEMS; x++) 15 System.out.println("\t" + array[NUMITEMS – x – 1]; 16 } 17 } Lines 1 and 2: The package java.io contains the File class, while java.util contains the Scanner class.

Line 6: "throws Exception" is discussed on page Four-15.

Line 8: The Scanner object accepts a File object, whose argument, in quotation marks, is the name of the text file. An advantage of object-oriented programming is that you can use objects without knowing exactly how they work.

Line 11. If you instantiate the Scanner object as in Line 8, then infile.nextDouble() takes care of the details of reading the text file. It even converts the string data into double data. Cool!

Line 12: At this point, the data from the text file has been stored in the array. Now you can close the file.

Remember! Data in a text file is always stored as a string. It is the programmer's responsibility to know whether to change those strings into doubles or integers, or to leave them as strings. In the next labs, sometimes you will use infile.nextDouble(), sometimes infile.nextInt(), and sometimes infile.next().

The infile.next()methods read the very first line of the file and then the next line, one by one, until the end is reached. You can't read a line twice. You can't read some lines, then go back up and start over. You have to read straight through the file from top to bottom. To get around those restrictions, we will read the text file data into an array. After that, you can access whatever data you want however you want.

Be careful! The name of a file is almost never "filename.txt"—that is a placeholder. Similarly, the name of the Scanner object does not have to be infile.

Four-23 Java Unit4 Lab03 Text Files

Objective To read data from a text file rather than from the keyboard. To read data from multiple files.

Background The contents of "data.txt" are shown here to the right. Rather than have the user type in all these values from the keyboard, your Driver03 program will read input directly from the text file itself.

Otherwise, the Lab03 problem is the same as the Lab02 problem, converting a series of Fahrenheit temperatures into Celsius temperatures. As you can imagine, this will make the code for your Driver03.java look a lot like the code from your Driver02.java.

In fact the only difference between the two programs is the manner of taking input. All storage of data, all calculations, and all output is exactly the same as it was before. You can copy those sections of your Driver02.java file directly into your Driver03.java file.

Really, the input portion of your file will also look very much as it did before, except that input will come from a Scanner object named infile rather than from a call to the JOptionPane.showInputDialog(). Because showInputDialog() returns strings, you had to turn the strings into doubles with Double.parseDouble( JOptionPane.showInputDialog() ). The equivalent scanner method, infile.nextDouble(), conveniently both reads the string and converts it.

Specification Filename Unit4\Lab03\data.txt. You do not have to open this file. Your program will open and process the data in this file.

Filename Unit4\Lab03\Driver03.java (load). As in Lab02, convert a series of Fahrenheit temperature into Celsius temperatures. This time, read the Fahrenheit data from "data.txt" into an array. Then process the array, turning all the Fahrenheit values into Celsius values. Express all calculations to two decimal places. Display the results in table form.

Test Data Go to www.tjhsst.edu/compsci.

Extension There is one piece of data we will often read from the keyboard even if our program’s ultimate intention is to read data from a text file—the name of the file itself. Use a JOptionPane to read in the name of the file to read from. Create text files "data2.txt" and "data3.txt" in the same format as data.txt. For now, you will have to make sure to put exactly twenty items in each file because your program is expecting to read exactly twenty items. That condition will be remedied in Lab04.

Four-24 Java Unit4 Exercises Lab03

Answer these questions about file input. 1a) For every line, explain what’s happening. 1. Scanner infile = new Scanner( new File("diskfile.txt") ); 2. String s = infile.next(); 3. double d = infile.nextDouble(); 4. int n = infile.nextInt(); 5. infile.close(); 6. System.out.print("You read: " + s + ", " + d + ", " + n);

1b) Trace the code above. If diskfile.txt contains Shane 234.5 18 what is the output?

1c) Trace the code above. If diskfile.txt contains 18 234.5 Shane what is the output?

1d) Trace the code above. If diskfile.txt contains Shane 234.5 what is the output?

2) Suppose you had to read from a text file a person’s Social Security Number, two semester averages (which could be decimals), and a letter final grade. Write the code to do that.

3) What is the return type of the method showInputDialog()? ______

4) What is the return type of the method next()? ______

5) What class is the method showInputDialog() defined in? ______

6) What class is the method nextDouble() defined in? ______

7) What is the return type of nextDouble()? ______

Four-25 Java Unit4

8) What package must you import to use Scanner()? ______

Four-26 Java Unit4 Discussion Exceptions

In Unit 1 you learned about different kinds of errors, namely, syntax errors, run-time errors, and logic errors. The programmer is completely responsible for syntax and logic errors, but sometimes is not responsible for run-time errors. The user could, for example, type in the wrong password, or the wrong file name. Still, the programmer would like to be able to handle this kind of error gracefully, say by offering the user another chance. Java responds to a run-time error by throwing an Exception, which allows the programmer to attempt to recover from the run- time error. Usually an exception is thrown in one part of the program and caught in another part of the program. It can be like a game of hot potato. First someone throws the hot potato to someone else, who throws it to someone else, who throws it to someone else, and so on until someone catches it and deals with it. If no one catches it, it eventually lands back at "the system," which summarily halts the program. That's not very graceful.

In Lab03, when the method readLine() encounters an input/output error, it throws an IOException. This exception is thrown to the method that called readLine(), which, in Lab03, was main(). In that lab, we decided not to deal with it there, but to pass it up to the system. We told our code to pass it to the system with the header

public static void main(String[] args) throws Exception

Usually a programmer prefers to catch the exception before it is passed on to the system. Java uses the try/catch block to do that. The basic structure is

try { //run some code which might throw an exception } catch (Exception e) { //if thrown, try to deal gracefully with the exception

} //the rest of the program

Because all sorts of things can go wrong, Java provides many sorts of exceptions. Go to the API and look up the Exception class. Then click on IOException and then on FileNotFoundException. That is the exception that we will be throwing in the next lab. In addition, you may have discovered other types of exceptions that can occur. Running off the end of an array will throw an ArrayIndexOutOfBoundsException. Incorrectly addressing an object throws a NullPointerException. Improperly casting throws a ClassCastException, and so on.

Besides the exceptions Java has provided, you can create your own. Here is an example you might find useful: try { //code to prompt the user to enter a denominator if (denominator == 0) throw new DivideByZero(); } catch (DivideByZero e) { System.out.println("Sorry, you cannot divide by zero!"); System.exit(0); } //the rest of the program

Four-27 Java Unit4 Lab04 Text Files and Try/Catch

Objective Read the first line of a text file to set the size of an array. Use try/catch blocks.

Background When users enter file names, they often mistype. If that happens, File() will throw a FileNotFoundException. The try-catch code below catches the exception, prints a message, and ends the program.

Scanner infile = null; try { String filename = JOptionPane.showInputDialog("Enter name of file:"); infile = new Scanner( new File(filename) ); } catch(FileNotFoundException e) { JOptionPane.showMessageDialog(null, "Error: File not found."); System.exit(0); }

Methods that could throw an exception should be in the try block. The attempt to recover should be in the catch block, which is only executed if needed. Note that the catch block shown above does not give the user a second chance. How can you modify the code above so that it prompts until the user enters a good file name?

Specification Filename Unit4\Lab04\MakeDataFile. Don’t change this program! When you run it, it creates "data.txt". The first number it creates is an integer, which determines how many random doubles it should create.

Filename Unit4\Lab04\data.txt. This is the data file. Your program will open this file and process the data. You should open the file to look at the data. Notice that the first line contains an integer, which in this case tells the number of numbers in the file. 6525 Filename Unit4\Lab04\Driver04.java. As in Lab01, process an array and 390.0202356936466 display the sum, max, min, and average. This time, read the data from a file 948.1569277972972 into the array. Use the first item of data in the text file, which is an integer, to 638.3505188754447 set the size of the array. Also, prompt the user to enter the filename, using the 574.3344213810659 try/catch structure shown above . . Test Data Go to www.tjhsst.edu/compsci

Extensions Compile and run MakeDataFile.java. Verify that the data in "data.txt" is different. Run Driver04.java again.

Modify the program so that it keeps prompting the user to enter a filename, until the filename is found.

Modify the program so that the user is given only three chances to enter a good filename. If the three chances are used up, display an appropriate message and terminate the program.

Four-28 Java Unit4 Lab04 Exercises #1

Below are the beginnings of three programming assignments. Read them carefully for all the information. 1. Your professor assigns you to write part of a program that processes a set of exam scores. She says there are exactly 181 exams. The scores are on a floppy disk in a text file "exam01.txt", one score per line. Write the code fragment to read the exam scores into an array.

2. Up till now, your professor has kept exam scores on paper. She assigns you to write a program so that someone can enter the exam scores into an array, from the keyboard. The number of scores has to be entered from the keyboard as well. She wants you to use good, friendly prompts.

3. Your professor teaches several courses. Each set of exam scores is saved to disk under different filenames. Each set of exam scores has an integer in the first line, which tells the number of exam scores in the file. Write the code fragment that prompts the user for the file name, reads the first line, and creates the empty array.

4. Actually, to calculate the sum, average, and max, you don’t need to store the data in an array. You can process the data from the text file on the fly, without knowing in advance how much data you have. Fill in the blanks:

Scanner infile = new Scanner( new File("data.txt") ); double sum = ____; double max = Double.MIN_VALUE; int count = ____; String oneLine = infile.next(); while( oneLine != null ) { double x = ______(______); sum = sum + _____; max = Math.max(______, ____); count++; oneLine = infile.next(); } System.out.println("Sum: " + ______); System.out.println("Average: " + ______); System.out.println("Max: " + ______); Four-29 Java Unit4 Lab04 Exercises #2

The contents of MakeDataFile.java are shown here. This file has been placed in your Unit04/Lab04 folder. Use this program and the Sun API to answer the questions below.

4 import java.io.*; 5 public class MakeDataFile 6 { 7 public static void main(String[] args) throws Exception 8 { 9 PrintStream outfile = new PrintStream(FileOutputStream("data.txt")); 10 11 int numitems = (int)(Math.random() * 5000 + 5000); 12 outfile.println(numitems); 13 14 for(int x = 0; x < numitems; x++) 15 outfile.println(Math.random() * 1000); 16 outfile.close(); 18 } 19 } 1) Why does Line 7 need throws Exception?______

2) What does Line 9 do? ______

3) What does Line 11 do? ______

4) What does Line 12 do? ______

5) What do lines 14 and 15 do? ______

6) In the code above, the PrintStream object is named ______.

7) In the code above, the object outfile is of class ______.

8) What kind of exception does the FileOutputStream constructor throw?______

9) Does the FileOutputStream class automatically create a text file for you if none exists?______

10) How many overloaded println() methods does the PrintStream class define?______

11) How many overloaded print() methods does the PrintStream class define?______

12) Why are there so many overloaded print() and println() methods?______

13) What two primitive types can't be arguments in the print() and println() methods? ______

14) What type of object is System.out?______

Four-30 Java Unit4 Discussion Shape Hierarchy

The shape classes represent geometric shapes numerically, not graphically. Note that the root of this hierarchy is an abstract class. Why must Shape be labeled "abstract", and what are the consequences of that?

public class Circle public abstract class Shape extends Shape { public Shape() {} Field Summary public abstract double findArea(); } private myRadius double Any time you study a new class, you need to ask yourself, "what does this class know about itself?"

Constructor Summary Part of the API for the Circle class is shown here to the Circle(double x) left. The Circle class is concrete. Question: what does Constructs a circle with initial radius that mean? specified by x. What private data should a circle know about itself? What methods does this Circle class know how to do? Method Summary What method must be implemented in the Circle class? Why? double findArea() Calculates and returns the circle's area. What private data should a rectangle know about itself? double findCircumference() What methods would be useful in rectangles? Calculates and returns the circle's circumference. Look at the API for Square. Square inherits methods from Rectangle. What methods does Square inherit? double getRadius() How can Square use Rectangle’s private data? What Returns the circle's radius extra methods are appropriate for squares? void setRadius(double x) Sets the radius to the input number. In implementing the methods, recall that the Math class contains a static constant Math.PI and a static method Math.sqrt() for calculating square roots.

Note that the Lab05 problem does not involve an array; Lab06 will make arrays of these objects. Your job in Lab05 is to make the methods work. Possibly a look at the Bug class from Unit 2, Lab05 will help you with the keywords and syntax for constructors, the get and set methods, and the return methods.

Lab05 Shapes

Objective Abstract classes, concrete classes, output to a text file.

Background

Four-31 Java Unit4

Driver05 is a tester program. It instantiates four objects and tests their methods. In the code below, a circle object is instantiated that has a radius of 75. The println() methods label the output nicely. Then, by using c.getRadius(), it "sends a message" to the object. The object "knows" how to respond to the message. The driver program is the client and the object is the server. Circle c = new Circle(75); System.out.println("Circle"); System.out.println("------"); System.out.println("Radius: " + c.getRadius()); System.out.println("Area: " + c.findArea()); System.out.println("Circumference: " + c.findCircumference());

Your job is to make the methods work. Perhaps a look at the Bug class from Unit 2, Lab05 will help you with the keywords and syntax for constructors, the get and set methods, and the return methods.

In this lab, the output will not go the monitor, but to a text file called "output.txt". The relevant line is:

System.setOut(new PrintStream(new FileOutputSteam("output.txt”)));

When your program runs nothing will appear on the monitor. All the output is saved on the disk. To view the results, open "output.txt" after your program is finished executing.

Specification Filename Unit4\Lab05\Shape.java. This abstract class is the superclass of all the other subclasses in this lab.

Filename Unit4\Lab05\Circle.java (load). Notice the private data field. Your job is to complete the constructor, the get and set methods, and the calculation methods.

Filename Unit4\Lab05\Rectangle.java. Implement the rectangle class. What private data should a rectangle know? What methods should a rectangle be able to do?

Filename Unit4\Lab05\Square.java. Implement the Square class, which extends Rectangle. Square will inherit many methods from Rectangle. Square will also use myBase and myHeight, which are private in Rectangle!

Filename Unit4\Lab05\Triangle.java. Implement the equilateral triangle class. What private data should an equilateral triangle know about itself? Every Algebra II student should know how to calculate the area of an equilateral triangle.

Filename Unit4\Lab05\Driver05.java (load). Complete the implementation of main() to test the four concrete shape classes.

Filename Unit4\Lab05\output.txt. Open and view the results of the program.

Lab05 Extension Javadoc

We have often directed you to look at the API because the API specifies what each class and method does. Even professional programmers refer to the API all the time. Because it is such an important document, Java has made it easy to produce the API document for each class you write. Suppose you write the Foo class. The command Four-32 Java Unit4 javadoc Foo will create, among other things, an .html file called Foo.html, which will be the API document. It will look just like the "real" API, including the descriptions, formatting, and light blue background.

You do have to follow certain conventions. For example, here is Circle.java with API information in the javadoc style. Each class and method is preceded by a helpful description. Each javadoc comment begins with /** and end with */ Some descriptions include an @ tag, such as @author, @version, @param, and @return, with extra information about author, version, arguments, and return types.

/***************************************************************** * A Circle is a Shape that maintains information about its radius. A * Circle knows how to return its radius, set its radius, calculate and * return its area, and calculate and return its circumference. * @author Torbert, e-mail: [email protected], website: www.mr.torbert.com * @version 7.14.2003 ****************************************************************/ public class Circle extends Shape { private double myRadius; /*************************************************************** * Constructs a circle with initial radius specified by x. * @param x initial radius ****************************************************************/ public Circle(double x) { myRadius = x; } /**************************************************************** * Returns the circle's radius * @return radius ****************************************************************/ public double getRadius() { return myRadius; } /**************************************************************** * Sets the radius to the input number. * @param x assigns x to myRadius ****************************************************************/ public void setRadius(double x) { myRadius = x; } Assignment: Add appropriate javadoc comments to your Rectangle.java file. Run the javadoc program on Rectangle.java to produce a well-commented Rectangle.html API. Ask your teacher how to access javadoc on your system. Discussion Polymorphism

You have to fill an array of shapes randomly in Lab06. An example of filling an array of shapes in a fixed manner is shown below.

Four-33 Java Unit4

Shape[] array = new Shape[4]; array[0] = new Circle(75); array[1] = new Square(50.0); array[2] = new Rectangle(30., 60.); array[3] = new Triangle(77);

Alternatively you could use:

Shape[] array = { new Circle(75), new Square(50.0), new Rectangle(30., 60.), new Triangle(77) };

We have actually seen this technique once before in Unit2. Recall that drawing a polygon required an array of x- coordinates created with a command like int[] xPoints = {50, 150, 200};.

Be careful! We cannot create Shape objects because Shape is an abstract class but we can create Shape[] objects. The Shape[] object is an array of Shape-type references that can be filled with objects created from the concrete subclasses of Shape. Like this:

[0] [1] [2] [3] array

Does this array store Shapes? Or does it store instances of circles, rectangles, and triangles?

Polymorphism , which is a superclass reference to a subclass object, is put into use with the code:

for(int k = 0; k < 4; k++) array[k].findArea();

Which of the four findArea() methods get executed? That depends on the type of object stored in each cell. Each object knows its own findArea() method. Remember that Java uses dynamic method binding so the method actually used at runtime is determined by the type of the object and not by the type of the reference. It’s a good thing, too, because in this case the references all point to the superclass Shape, and Shape doesn’t even have a body for the findArea() method. The reference points to a Shape, the superclass of the actual object, which implements findArea(), which gets executed.

Lab06 Array of Shapes

Objective Construct an array of objects. Use polymorphism. String representation of objects.

Four-34 Java Unit4

Background There are two steps in constructing an array of objects. First you must construct the array itself, then you must construct each individual object. Since arrays in Java are treated as objects you must use the keyword new twice in this process: once for the array and once for the contents of the array.

For example: Foo[] array = new Foo[100]; //create an empty array for(int k = 0; k < array.length; k++) //fill it array[k] = new Foo(); // with objects

Be careful! The array is of type Foo[], the contents of the array are of type Foo, and the constructor is Foo().

The method toString() can be called on any object, because the Object class, which is the root of all Java classes, contains a default implementation for the method toString(). For any object x, x.toString() returns the name of the object’s class, the @ sign, and the hexadecimal address where the object is stored inside your computer. For example, given an object x of type Foo, then x.toString() might produce the string representation "Foo@45a877".

Actually, we have been calling toString() for primitives every time we converted a number to a string, with e.g. System.out.println(""+x). The (""+x) is a shortcut that uses toString(). If x is a primitive type (i.e., integer, double, Boolean, char, and four others) then (""+x) converts the value into its string representation. For example, if int x=8, then (""+x) converts 8 to the string representation "8". That conversion is, thankfully, just what we expect for numbers.

Specification Filename Unit4\Lab05\Shape.class. Copy from the Lab05 folder. Filename Unit4\Lab05\Circle.class. Copy from the Lab05 folder. Filename Unit4\Lab05\Rectangle.class. Copy from the Lab05 folder. Filename Unit4\Lab05\Square.class. Copy from the Lab05 folder. Filename Unit4\Lab05\Triangle.class. Copy from the Lab05 folder. Filename Unit4\Lab06\Driver06.java. Create an array of some largish, random size. Fill each cell of the array by instantiating different objects (either circle, rectangle, triangle, or square) at random. Do not merely alternate among the four in a predictable fashion! Also make sure to create the individual objects themselves at random, i.e. two circles should have different, randomly-generated radii. After the array is filled, output the area of each object and the string representation of each object to the file output.txt.

Filename Unit4\Lab06\output.txt. When your program runs nothing will appear in the DOS window. Open output.txt after your program is finished executing to view the results.

Test Data Go to www.tjhsst.edu/compsci.

Extension: Replace array[x].findArea() with array[x].getBase(). Explain why it won't compile.

Four-35 Java Unit4 Exercises Lab06

1) Explain what Lab06 has to do with polymorphism.

2) Fill in the names of the instance methods for the Circle class. Notice that myRadius is private. Circle myRadius

Complete this scavenger hunt using Sun’s on-line Java API.

3) What package is your Rectangle in? ______

4) What package is Sun’s Rectangle in? ______

5) What is the superclass of Sun’s Rectangle? ______

6) What package is this superclass in? ______

7) What are the names of Sun’s Rectangle’s four fields? ______

8) What type of variables are these fields? ______

9) Are Sun’s Rectangle’s fields public or private? ______

10) What type is the argument of the second Rectangle constructor? ______

11) What two pieces of data does the Rectangle class keep track of? ______

12) Scanner is in package ______. Scanner is used for ______

13) JOptionPane is in package ______. JOptionPane is used for ______

14) PrintStream is in package ______. PrintStream is used for ______

Four-36 Java Unit4 Discussion do-while loops

You have seen a while loop.

while(CONDITION) { COMMANDS; }

The do-while loop is a similar structure.

do { COMMANDS; }while(CONDITION);

The difference between these two control structures is that the while-loop might not ever execute its commands at all. If the while-loop condition is false initially then the loop is skipped.

On the other hand, a do-while loop will always execute its commands at least one time. It keeps on looping until the condition is true. This behavior can be very useful, as we will see in the next lab.

The while is a precondition loop and the do-while is a postcondition loop.

Decimal Formatting

Say you want to format a double type value (e.g. 1.2345678) to two decimal places (to 1.23). One option is:

x = (int)(x * 100) / 100.0;

If x equals 1.2345678, then x * 100 is 123.45678, which when cast to an integer yields 123. Dividing this by 100.0 results in the desired 1.23. Make sure to use 100.0 as shown because 123 / 100 is just 1. (Why?) To round positive numbers add 0.5 before casting (-0.5 for negative numbers).

Another option is to use the DecimalFormat class from the java.text package. The desired format pattern is passed as a string to the DecimalFormat constructor. The method format() is used to convert a double type value to a string representation with the desired formatting.

DecimalFormat d2 = new DecimalFormat("0.00"); String s = d2.format(x);

There are advantages and disadvantages to each of these options. It is up to you to use whichever is most appropriate to any one particular situation.

Be careful! The result of the format() method is a string, not a number. A string.

Four-37 Java Unit4 Lab07 Luck of the Roll, Part II

Objective do. . .while loop. Dice class.

Background This lab conducts three experiments with dice. How many rolls does it take to roll boxcars (double 6’s)? How many rolls does it take to roll doubles? If we roll 100 times, how many rolls does it take to get doubles, on average?

What tools does the Dice class give us? Look at the Unit4 API. doubles() returns a Boolean, which is true/false. What do you think doubles() tests for? roll() is void. What do you think roll() does? toString() reports the results of a dice throw. This toString() overrides the toString() that is inherited from Object. total() returns an integer. What do you think total() does?

What private variables would it make sense for a Dice class to know?

The API doesn’t mention that the Dice class also has one private helper method. What is it used for?

Driver07.java is shown here to the right. A Dice object named d is created and a count variable is initialized to zero. The count is incremented each time we roll the dice and we roll the dice until we get double-6’s (boxcars).

Notice that we use a do-while loop here because we know that at least one roll is required.

Specification Filename Unit4\Lab07\Dice.java (load). Complete the implementation of the class.

Filename Unit4\Lab07\Driver07.java (load). Add code to determine how many rolls it takes to get any doubles, not necessarily boxcars. When you finally roll doubles, report the values of the doubles. Then add code to determine how many rolls it takes on average to get doubles over 100 trials.

Test Data Go to www.tjhsst.edu/compsci. Four-38 Java Unit4 Exercises Lab07

1) There are three kinds of loops. What are they? ______

2a) What is the output of this loop? int limit = 6; for (int count = 1; count<=limit; count++) System.out.println(count + " squared is " + count * count);

2b) Rewrite the loop as a while-loop.

2c) Rewrite the loop as a do-while loop.

3) What is the output of this loop? int sum = 0, count = 0, grade; grade = Integer.parseInt(JOptionPane.showInputDialog("Enter a grade:")); while (grade >= 0) { count++; sum += grade; grade=Integer.parseInt(JOptionPane.showInputDialog("Enter a grade:")); } System.out.println("the average is " + sum/count);

3b) Rewrite the loop as a do-while loop.

4) Since a while-loop tests the Boolean condition at the ______of the body, the body ______does not execute.

Four-39 Java Unit4

5) Since a do-while loop tests the Boolean condition at the ______of the body, the body ______executes at least once. Discussion Strings

A "string" to a computer scientist is a sequence of characters. "ABC", "1.23", and "123" are all examples of strings. In Java, strings are implemented as objects, instances of the String class, but in many ways strings act unlike other objects. For example, you can instantiate a string without using the keyword new.

String s = "hello";

The only overloaded operators for objects that Java allows are for string concatenation.

String str = "Concat"; str = str + "enat"; str += "ion";

"Concatenate" means to add on to. The three commands shown above produce the string "Concatenation".

We often want to compare strings for equality, but we don’t use ==. Instead, we use the equals() method. The symbols == is used to compare primitives. Whenever you compare objects, you must use equals(). Any object can call equals() because there is a default implementation in Object. The concrete class, in this case String, overrides that equals() by defining an equals() that is appropriate to strings, i.e., the letters match.

Using the assignment statements above, str.equals("Concat") returns true, and str.equals(s) returns false.

The case of the letters matter, so that the string "Hello" and the string "hello" are not the same. s.equals("hello") returns true but s.equals("Hello") returns false.

You could also compare them the other way around, because string literals are objects themselves. For instance, "hello".equals(s) returns true but "Hello".equals(s) returns false.

Strings are immutable. Once a string object is created it can never be changed, which is equivalent to saying that strings do not have set methods. In the concatenation example above, it looks like there is only one string, but actually there are three different immutable string objects that exist at one time or another: "Concat", "Concatenat", and "Concatenation". The str reference is changed to point to three different objects.

Underlying every string is an array of characters. The primitive type char creates space to store single characters. s [0] [1] [2] [3] [4] array ‘h’ ‘e’ ‘l’ ‘l’ ‘o’

Of course the string is much more than just an array of characters. Check the extensive String class API for more information regarding strings and string methods. Be sure to look up equals() and compareTo().

Four-40 Java Unit4 Lab08 Dictionary

Objective Work with an array of strings.

Background As in previous labs, we will be reading data from the hard drive into an array, processing the array, and outputting the results. Since the data in the previous labs was numerical, we had to parse the input strings into numbers. In this lab, since the data is ordinary words, not numbers, we do not have to parse the input data. An ordinary word to the computer is a String object, which contains a sequence of characters. Computer scientists call them "strings."

After reading in the string data, similar to what you did in Lab04, your array would look like:

[0] [1] [2] [3] [4] [45392] array "Aarhus" "Aaron" "Ababa" "aback" "abaft" . . . "Zurich"

After the array is set up, we will want to enter a word and search the array for that word. (We are making a simple spell-checker.) It would be nice to prompt over and over. One way to loop repeatedly is to use an infinite loop that keeps prompting the user until the user wants to stop, in this case by typing "-1".

while(true) { String myWord = JOptionPane.showInputDialog("Word? (Type –1 to quit:)"); if(myWord.equals("-1") break;

//Your code goes here. }

This would normally loop without ending, since the condition of the while-loop is hard coded to be true. However, when the user types in "–1" (without quotation marks) then the break statement ends the infinite loop.

Specification Filename Unit4\Lab08\words.txt. Open this file and look at it. The first item in words.txt is an integer indicating how many words are in the file. Driver08 will open this file and read the list of words into an array.

Filename Unit4\Lab08\Driver08.java. Let’s make a simple spell checker. Read the contents of words.txt into an array of strings. (The first item in words.txt is an integer indicating how many words are in the file.) Prompt the user to enter a string. Search the array and indicate whether or not that string is a valid word based upon whether or not it appears in words.txt. If the word is valid, also display the word’s index (its position) in the array. Continue this spell-checking process until the user wants to quit by typing "-1" (without the quotation marks). Then print "goodbye" and exit the program. Yes, "dog" is a word, #13380. Yes, "god" is a word, #18516. Test Data Sorry, "God" is not a word. Go to www.tjhsst.edu/compsci. Good-bye. Extension Look at the String API. Change your code so that it compares strings while ignoring capital letters.

Four-41 Java Unit4 Exercises Lab08

1) What is the output of the following code fragment? String test = "abcde"; String greeting = "How are you?"; System.out.println(test.length()); ______

System.out.println(test.charAt(1)); ______

System.out.println(test.indexOf("c")); ______

System.out.println(test.substring(3)); ______

System.out.println("ab\ncd\te"); ______

System.out.println(greeting + " " + test); ______

System.out.println( toUpperCase(test) ); ______

System.out.println( test.equals("abc") ); ______

System.out.println( test.compareTo("Abcde") ); ______

Complete this scavenger hunt using Sun’s on-line Java API.

1) What type of argument is required by the String method charAt()? ______

2) What is the return type of the String method charAt()? ______

3) The method charAt() is similar to the ______operator for arrays.

4) How many String methods are there that begin with compare…? ______

5) How many String methods are there that begin with equals…? ______

6) How many overloaded indexOf() methods does the String class define? ______

7) How many overloaded lastIndexOf() methods does the String class define? ______

8) All arrays have a public field length. Does String have a public field length? ______

9) How many overloaded substring methods does the String class define? ______

10) How many String methods are there that have the form toXXXXXCase? ______

Four-42 Java Unit4 Discussion An Array of Text Boxes

An array of text boxes provides a good visual reinforcement of the structure of an array. The GUI display looks a lot like our box diagram for an array of objects.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 array

18 JTextFields:

18 strings "3 "4 "4" "2" "3" "3" "2" "2" "2" "2" "1" "2" "1" "3" "2" "4" "1" "3"

Notice that each cell in the array does not store the data directly, as it did in previous labs. Instead, each JTextField is itself an object. To access the private data in the JTextField, you’ll need to use its get and set methods. Remember also that a JTextField, like every GUI component, works with strings, not integers. That means that you will always be converting from numbers to strings and back again.

As usual, creating an array of objects is a two-step process (lines 18 to 21).

Adding 18 JTextFields to the GUI is a third step (line 22).

The fourth step, to put data into the 18 JTextFields, is left for you as part of the lab.

The fifth step is to process the data in the JTextFields. You’ll be writing the code that executes when the buttons are clicked.

Four-43 Java Unit4 Lab09 Miniature Golf

Objective Work with an array of GUI components.

Background This lab models a scorecard for a round of miniature golf. It also processes the array to calculate three different statistics: the total for the round, the numbers of holes-in-one (aces), and the hole with the highest score. In golf the lowest score is the winner, not the highest score.

Specification Filename Unit4\Lab09\Driver09.java. Open and look. This is our standard GUI driver. You don’t have to write any code. Notice that Driver09 instantiates Panel09, which "isa" JPanel.

Filename Unit4\Lab09\Panel09.java. Open and look. You don’t have to write any code here. Notice that Panel09 creates the buttons, the listeners, and the output label (the "Total Score: 46") at the top of the panel. Panel09 also instantiates ScoreCard09, which also "isa" JPanel.

Filename Unit4\Lab09\ScoreCard09.java (load). Notice that ScoreCard09 has an array of JTextFields as private data. Notice that ScoreCard also displays 18 JLabels and 18 JTextFields. ScoreCard09 implements four methods that execute when Panel09’s buttons are pushed. Complete the implementation of the four methods: randomize(), findTotal(), findAces(), and findHardestHole(). If several "hardest holes" have the same score, show the first one.

Test Data Go to www.tjhsst.edu/compsci.

Four-44 Java Unit4 Discussion Binary Numbers

Humans use a base ten number system for day-to-day arithmetic. Our decimal system is similar to other number systems in its use of place value. For instance:

937.5 = 9 * 100 + 3 * 10 + 7 * 1 + 5 * 0.1

The units place is always immediately left of the decimal point. The units place is the "middle" of the number. The digit in the units place has a value equal to itself, or a value equal to the product of itself and the base of the number system raised to the zero power (which is always one).

To the left of the units place the powers that the base of the number system is raised to increase. To the right of the units place the powers that the base of the number system is raised to decrease. A digit’s value is determined by the product of itself and the base of the number system raised to the power corresponding to the digit’s place.

Digit: 9 3 7 5 Power: 2 1 0 -1 Place Value: 100 10 1 0.1 Digit’s Value: 900 30 7 0.5

The same procedure holds in number systems with other bases, only with increasing and decreasing powers of the base for that number system instead of ten. Always we are restricted to those digits less than the base itself.

1100 0101 = 1*128 + 1*64 + 0*32 + 0*16 + 0*8 + 1*4 + 0*2 + 1*1

Again we have increasing powers of the base, but now the base is two. This is the binary number system. We can determine the sum of products in order to convert to decimal. Since there are only two digits (zero and one) and since zeros destroy products and ones don’t affect them, we write:

1100 0101 = 128 + 64 + 4 + 1

So 110001012 = 19710. The subscript indicates the base of the number system. In binary we often separate out the digits of a number in groups of four, similar to using commas for large numbers in base ten. Each binary digit is called a bit. Eight bits are called a byte. Always remember that 210 = 1024.

When working with binary numbers it helps to know the powers of two.

Digit: 1 1 0 0 0 1 0 1 Power: 7 6 5 4 3 2 1 0 Place Value: 128 64 32 16 8 4 2 1 Digit’s Value: 128 64 0 0 0 4 0 1 Lab10 Reversal of Fortune

Objective Solve a problem involving an array of labels.

Four-45 Java Unit4

Background The first digit is the one furthest to the right. It is the digit with the smallest place value.

The last digit is the one furthest to the left. It is the digit with the largest place value.

Randomize() means to set each digit to either a zero or a one at random. Do not flip a coin and then set all the digits to zero or all the digits to one. Each digit should be randomly assigned a zero or a one independent of the other seven digits.

Reverse() means to swap the first and last digits, swap the second and seventh digits, swap the third and sixth digits, and swap the fourth and fifth digits.

Shift() means to make each digit equal to its neighbor to the right, effectively shifting all the digits down one place to the left. The last digit’s value is lost and the first digit’s value becomes zero.

Rotate() is exactly like shift except rather than losing the last digit’s value and making the first digit zero the first digit gets the last digit’s value.

Specification Filename Unit4\Lab10\Driver10.java (load). Driver10 is our usual driver, instantiating and calling Panel10.

Filename Unit4\Lab10\Panel10.java (load). Open this file. Notice that Panel10 "hasa" Display10. Panel10 also creates the buttons, listeners, and method calls.

Filename Unit4\Lab10\Display10.java (load). Complete the implementation of four methods: randomize(), reverse(), shift(), and rotate().

Test Data Go to www.tjhsst.edu/compsci.

Extension Filename Unit4\LabXX.java. Enter an integer and output its binary representation. Implement two buttons, Convert and Step. See the on-line demo.

Four-46 Java Unit4

Lab11 Scoreboard11 Guess the Number (extension)

Objective To program a game that uses an array of buttons.

Background The game is played as follows:

1. Pick a number from 1-25. Display11 2. The machine will tell you one of three things: A. Congratulations, you picked the right number. B. Sorry, your guess was too high. C. Sorry, your guess was too low. 3. Pick another number. Panel11

The game is played until one of two things happens: the player guesses the number (win) or the player does not guess the number and runs out of tries (loss). The player gets four tries to guess the number.

Be careful! The array of buttons is displayed in a grid layout. This causes the array cells to wrap when they get to the end of each row. Do not be deceived. The array is linear. It has only one dimension. The rows and columns you see on the screen are only significant to the GUI display, not the logic of the game.

Specification Filename Unit4\Lab11\Driver11.java (load).

Filename Unit4\Lab11\Panel11.java (load). Panel11 "isa" JPanel and "hasa" Display11. Panel11 implements the listeners and the label at the bottom. You will have to complete five methods that change the label and then call the appropriate method in Display11.

Filename Unit4\Lab11\Display11.java (load). Display11 "isa" JPanel. It instantiates 25 buttons. As the user makes his/her guess, the buttons’ foreground and background colors change. Look at the demo.

Test Data Go to www.tjhsst.edu/compsci.

Extension Let the user play the game as many times as he or she wants. Keep track of the wins, the games played, the streak of wins, and the longest streak. Add a scoreboard object to the northern region of Panel11. Call the scoreboard’s methods from Panel11. JPanel Here is the (partial) class diagram. Not shown are about 15 other classes including JButton, Color, Font, Driver Panel Display JLabel, String, 3 layout managers, JFrame, DecimalFormat, etc. Scoreboar Listeners

Four-47 Java Unit4 Discussion Two-Dimensional Arrays (Matrices)

The arrays you have worked with so far have been one-dimensional arrays. To recap:

double[] array1 = new double[10]; boolean[] array2 = {true, true, false, true, false, false, false}; String[] array3 = {"dog", "cat", "eat", "pie"}; Foo[] array4 = new Foo[100]; for(int k = 0; k < array4.length; k++) array4[k] = new Foo();

Any primitive type or object type can be stored in an array. Use brackets [] to indicate that you are creating an array of doubles, booleans, Strings, or Foos rather than a single double, boolean, String, or Foo. The array itself is stored as an object regardless of what type of data stores. The indices of the array are always numbered with integers starting from zero. The public field length indicates the number of cells in the array. The brackets are used to access the contents of individual cells. Creating an array of objects is a two-step process: first create the array, then create the objects to fill the array.

A two-dimensional array is a matrix. Almost literally, a matrix is an array of arrays. For instance:

double[][] matrix = new double[2][3];

This command creates a matrix named matrix with two rows and three columns. Of course the name of a two- dimensional array does not have to be matrix. Always indicate the rows first, then the columns.

matrix [0] [1] [2] [0] [1]

To access any one cell you must specify both the row and the column. Some examples:

matrix[0][1] = 3.7; for(int r = 0; r < matrix.length; r++) //assigns 1.0 to each matrix[r][0] = 1.0; //cell in col 0.

for(int c = 0; c < matrix[0].length; c++) //assigns 2.0 to each matrix[1][c] = 2.0; //cell in row 1

for(int r = 0; r < matrix.length; r++) //sets all values for(int c = 0; c < matrix[0].length; c++) //in the matrix matrix[r][c] = 0.0; //to 0.0

The number of rows is indicated by matrix.length(). In the example above, matrix.length() returns 2. The number of columns is matrix[0].length, which returns 3 in the example above. To fill one column, fix the column value and loop over the rows. To fill one row, fix the row value and loop over the columns. To fill the entire matrix, loop over both the rows and the columns.

Be careful! Always specify the row first and then the column. You can think of RC Cola, which stands for Royal Crown Cola everywhere else but in Computer Science it means Row first, then Column.

Four-48 Java Unit4 Lab12 Miniature Golf, Foursome

Objective To process 2-dimensional arrays.

Background You solved the miniature golf problem in Lab09 for one player only. One player needed a one-dimensional array to keep track of his or her score.

In Lab12 you have a foursome. A foursome needs a two-dimensional array to keep track of all four players’ scores over eighteen holes of golf. Player one gets all the scores in row zero, player two gets all the scores in row one, and so on.

Be careful! Both the rows and the columns of a matrix are zero indexed. The upper- left corner of the matrix is position 0, 0.

Specification Filename Unit4\Lab12\ScoreCard12.java (load). Complete the implementation of five methods: randomize(), findTotal(), findAces(), findHardestHole(), and findHardestHole(int x).

Filename Unit4\Lab12\Panel12.java (load). Panel12 "hasa" ScoreCard. Panel12 also implements the buttons, the listeners, and all the output labels.

Filename Unit4\Lab12\Driver12.java (load). Compile and run.

Test Data Go to www.tjhsst.edu/compsci.

Four-49 Java Unit4 Lab13 Project Battleship

Objective To use matrices.

Background Your job is to write three methods: placeShip, actionPerformed, and actionPerformed. placeShip: To flip a coin use int coin = (int)(Math.random() * 2 + 1);. Simulate flipping a coin to decide whether the ship will be oriented vertically or horizontally and pick a random position on the board to represent the starting point for the ship. If the ship is vertical then this random point represents the top of the ship; if horizontal then the left-most part of the ship. The ship is four blocks long so make sure you don’t go out of bounds. Important! The placeShip method does not reference the board of buttons because the user should NOT be able to see the ship. The ship is stored in the integer matrix by changing the zeros to ones. This will be used in Handler1’s actionPerformed to tell whether a particular shot was a hit or a miss. actionPerformed (Handler1): This is where most of the stuff happens. Since the user has pressed a button, subtract one from the number of torpedoes. Each handler object keeps track of private integers myRow and myCol that tell you where on the board a particular button is. Use myRow and myCol with the integer matrix to determine whether this shot was a hit or a miss. The user wins by getting four hits. The user still wins even if he or she runs out of torpedoes with the fourth hit. The user loses by running out of torpedoes without having sunk the ship. actionPerformed (Handler2): This happens when the user presses the reset button. Reset the integer matrix to all zeros and then call placeShip to put a new battleship on the board. Reset everything else to its original state.

board (2D array of buttons) matrix (2D array of integers) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Specification Filename Unit4\Project\Battleship.java (load). Complete the implementation of the three methods described above.

Filename Unit4\Project\BattleshipDriver.java (load). Compile and run.

Test Data Go to www.tjhsst.edu/compsci.

Four-50 Java Unit4 Lab14 Tic-Tac-Toe

Objective To use a matrix.

Background The game is played as follows:

1. Pick a location on a 3 x 3 board 2. One of three things will happen: A. Congratulations, you have won the game. B. Sorry, the game is over in a tie. C. The game is not over. 3. Alternate turns with the other player. 4. Pick a new location that has not already been picked.

The game is played until one of two things happens: either one player gets three of their pieces in a row (win) or no one gets three in a row and we run out of empty locations (tie). Players can win with three in a row horizontally, vertically, or diagonally. Let the users play the game as many times as they want and keep track of each player’s wins and the ties (cat’s game) over time.

Specification Filename Unit4\Lab14\Panel14.java. Panel14 "hasa" Gameboard14 and a Scoreboard14. It also has the reset button and the "winner" label. Panel14 has a listener method to check for wins or ties (after 9 moves have been made) every time the gameboard buttons are pressed.

Filename Unit4\Lab14\Gameboard14.java. The gameboard has 9 tic-tac-toe buttons. It has the reset() method to start things off, a winner() method to check for winners, a count-up-to-9 method, and a freeze() method, which is called at the end of a game.

Filename Unit4\Lab14\Scoreboard14.java. The scoreboard counts and displays the wins for X and O and the ties (the cat’s games.) Notice also that the scoreboard above has a yellow background behind the X, showing that it is X’s turn. Therefore, the scoreboard has a toggle() method that moves that yellow background as the players play.

Filename Unit4\Lab14\Driver14.java.

Extension Have the person play against the computer. Let the computer always play the 0. Make the computer play an intelligent tic-tac-toe game.

Test Data Go to www.tjhsst.edu/compsci.

Four-51 Java Unit4 Lab15 Mastermind

Objective To use arrays.

Background The game is played as follows:

1. The computer selects a random sequence of four colors. Order matters, but colors may be repeated. The possible colors are red, blue, green, yellow, orange, and purple.

2. The player guesses a sequence of four colors.

3. The computer informs the player as to how many colors were guessed correctly in the correct location (white pegs) and how many colors were guessed correctly but in the wrong location (black pegs). If a color is repeated in the answer and a player includes that color in part of his or her guess, the color may be counted only once in the information provided by the computer.

4. The player then makes another guess.

The game is played until one of two things happens: either the player guesses the answer pattern (win) or the player does not guess the answer pattern and runs out of guesses (lose). Players get a maximum of eight guesses before the game ends. Let the player play the game as many times as he or she wants and keep track of the wins and losses over time.

Specification Filename Unit4\Lab15\UpToYou.java.

Test Data Go to www.tjhsst.edu/compsci.

Four-52

Recommended publications