Title: Questions before we Start
1Questions before we Start?
- Any questions on HW?
- HW 5--3 classes (PayrollApp (client), Payroll,
Employee). Gave you 90 of PayrollApp.
2Week 06 - a
- Nested Loops
- Two-Dimensional Arrays
- Computer Graphics
- Vectors
3Sample Programs Referenced(code located in
course folder)
- java arrays.BoolArrayLab
- Multiplication Table
- Magic Triangle
- Eight Queens
- Sudoku (handout)
- Piet Mondrian Art
- "Turtle" Graphics
- VectorExercise
42-dimensional boolean array(AnimatedIllustrations
)
5Nested for Loops
- Nested loops frequently used to process
two-dimensional arrays - Often body of inner loop is where the main
computation is done - Example
- for (i 0 i lt m i)
- before inner loop
- for (j 0 j lt n j)
- body of inner loop
- after inner loop
6Nested Loops
7Multiplication Table Problem
- A Java program to produce a multiplication table
- Let the user specify the largest number
- See Multiplication Table Project
8Dependent for Loops
- Sometimes the extent of the inner nested loop
will depend on the index value of the outer loop - What is the result of the following code?
- for (i 0 i lt 3 i)
- System.out.print("i " i " j ")
- for (j 0 j lt i j)
- System.out.print(" " j)
- // end of "j" loop
- out.println()
- // end of "i" loop
9Nested Loop Contained inOther Statements
- What would be printed by the following?
- "Volunteer" to the Board
- for (int i 1 i lt 10 i)
- if (i 2 0) // i even
- for (int j 1 j lt i/2 j)
- System.out.print()
- else // i odd
- for (int k 1 k lt 5 i/2 k)
- System.out.print()
- System.out.println()
10Output
11Magic Triangle
- Input a word (say GISMO), print out in a
triangle - G
- I I
- S S S
- M M M M
- O O O O O
- Need spaces to decrease before printing each row
- Print a space between letters
- Try running the project (enter ABRACADABRA)
12Magic Triangle Code
- public static void main()
- String word JOptionPane.showInputDialog(
"Please enter a magic word.") - int size word.length()
- for (int row1 rowltsize row)
- char ch word.charAt(row-1)
- for (int colrow colltsize col)
- System.out.print(" ")
- for (int col1 colltrow col)
- System.out.print(ch" ")
- System.out.println()
- // end of "row" loop
- // end of main program
13Two-Dimensional Arrays
- Used to store tabular data
- Declaration and allocation similar to one
dimensional arrays - Need to specify both the number of rows and
columns during allocation - Example
- final int COLS 6, ROWS 5
- double someTable
- someTable new doubleROWSCOLS
- or
- double someTable new doubleROWSCOLS
14Two-Dimensional Arrays
- Other examples?
- Several HW scores for list of Students
- 52 weeks of Pay for 150 Employees
15Arrays of Arrays
- Writing
- someTable new doubleROWSCOLS
- is shorthand for
- someTable new doubleROWS
- for (int i 0 i lt ROWS i)
- someTablei new doubleCOLS
16PopulatingTwo-Dimensional Arrays
- final int ROWS 4, COLS 3
- String someTable new StringROWSCOLS
- int r, c
- // reads strings needed to fill
- // someTable one row at a time
- for (r 0 r lt ROWS r)
- for (c 0 c lt COLS c)
- someTablerc JOptionPane.showInputDialog(
"") - What value would you enter 1st? 2nd? 3rd? 6th?
- How many values would we have to read from the
keyboard? - Later in the term we will see how to read data
from a file
17Initializing Two-Dimensional Arrays
- double energyTable
-
- 18.9, 19.4, 34.2, 3.9, 5.7, 0.3,
- 19.1, 19.3, 33.6, 3.0, 6.2, 0.2,
- 18.8, 19.6, 32.9, 3.1, 6.6, 0.2,
- 18.9, 20.3, 33.5, 2.8, 6.7, 0.2,
- 19.6, 20.8, 33.8, 3.1, 6.5, 0.2
-
18Computing Row Totals
19Computing Row Totals
- double rowTotals new doubleROWS
- for (r 0 r lt ROWS r)
- // compute total for row r
- rowTotalsr 0.0
- for (c 0 c lt COLS c)
- rowTotalsr rowTotalsr
someTablerc -
- How would you compute column totals?
20Two-Dimensional Arrays and length
- someTable.length is number of rows in someTable
- someTablei.length is number of columns in row i
of someTable - In Java rows can be of different lengths!
- Example
- int someTable new doubleROWS
- for (int i 0 i lt someTable.length i)
- someTablei new inti 1
- out.println("Length of row "i" is "
- someTablei.length)
-
- Draw a diagram
21Chess Queen Attack ProblemBlueJ
22Queen Attack Client
- public static void main(String args)
- QueenAttack board new QueenAttack()
- int row Integer.parseInt(JOptionPane.showInput
Dialog( - "Row 1-8 on which to place
queen?")) - int col Integer.parseInt(JOptionPane.showInput
Dialog( - "Column 1-8 on which to place
queen?")) - board.placeQueen(row,col)
- board.display() // could display as text or
graphics - // end of main method
23QueenAttack class(top-down approach)
- public class QueenAttack
- private char gameBoard new char88
- public void placeQueen(int row, int col)
- System.out.println("placeQueen on row "row
" col "col) - // end of placeQueen method
-
- public void display()
- System.out.println("display gameBoard")
- // end of display method
-
- // end of EightQueens class
24placeQueen Method
- public void placeQueen(int row, int col)
- for (int r1 rlt8 r)
- for (int c1 clt8 c)
- if (rrow ccol
Math.abs(r-row) Math.abs(c-col)) - gameBoardr-1c-1 'x'
- gameBoardrow-1col-1 'Q'
- // end of placeQueen method
25display Method
- public void display()
- for (int row 1 row lt 8 row)
- for (int col 1 col lt 8 col)
- System.out.print(" "gameBoardrow-1col-1
) - System.out.println()
- // end of row loop
- // end of display method
26Volunteer to the Board...
first
27Java BREAK
28Computer Graphics
- Computer Graphics is the study of methods of
representing and manipulating images - A two-dimensional array can be used to represent
the image to be displayed - This array is called a frame it has one entry
for each pixel giving its color - Applets have this Graphics display area created
for them - The number of pixels in the frame is the
resolution the display device
29Computer Art
- Piet Mondrian is a famous 20th century painter
- So called "Modern Art"
- Several paintings consisted of abstract black
lines on a white canvas with red, blue or yellow
rectangles - Mondrian Project is running on Course Schedule
web page - Click for new painting
- Paintings are for sale proceeds will benefit the
"CS Professors' Pizza Fund" ?
30Turtle Graphics(related to Lab 8)
- Interactive Applet
- Again, the drawing box is being used as a
2-dimensional array. - Turtle can move up/down, left/right
- 7-pixel steps in the direction it is heading
- Turtle Code at end of today's lecture notes
- Talk about it more once we have covered "Button"
class
31Traverse a Maze
- Classic 2-dimensional program
- See CSc-105 Home Page (with Maze)
- More on Mazes after we cover Recursion
32Arrays vs. Vectors
- Arrays
- Used to store collections
- Must allocate a fixed number of cells
- Can store either primitive values or objects
- All elements must be same data type
- Difficult to insert/remove values in the middle
- Must move other elements manually
- Dont behave like classes
- Vectors
- Used to store collections
- Can grow or shrink as needed (dynamic)
- Can only store objects
- Elements may be of different data types
- Provide methods to add, retrieve, insert, or
remove elements in the middle of a vector - Regular Java class - part of the java.util library
33Declaration and Allocation
- Declaration syntax
- Vector name
- Note the data type of the objects that will be
stored in the vector is not specified. (All are
assumed to be of type Object.) - Allocation syntax
- name new Vector()
- Note no size needed (can be specified)
- Declaration and allocation
- Vector name new Vector()
34Methods that Insert Objects into a Vector
- addElement(Object obj)
- Appends the object obj to the end of the vector
and increases its size by 1 - insertElementAt(Object obj, int i)
- Inserts the object obj at index i and shifts all
the elements above location i up by 1. Also
increases the size by 1 - setElementAt(Object obj, int i)
- Replaces the object at location i with the object
obj - NOTE All of the above methods are of type void
35Exercise"Volunteer to Board"
- Draw a diagram showing the contents of memory
after each of the following statements are
executed - Vector x new Vector()
- x.addElement(Mary)
- x.addElement(Tom)
- x.insertElementAt(Ann, 0)
- x.setElementAt(Fred, 1)
36Accessing Elements in a Vector
- Method elementAt(int i)
- Returns an Object type reference to the element
at index i of the vector - Example of use
- Object y x.elementAt(2)
- Why Object? What is Object?
- Experiment with Vector Exercises project
37Other Methods of theVector Class
- int size()
- Returns the number of elements in the vector
- NOTE not length()!
- void removeElementAt(int i)
- Removes element at index i
- Moves the rest of the elements down one
- Decreases the size by 1
- String toString()
- Returns a String representation of the vector
enclosed in brackets - Uses the toString methods of the individual
elements - Puts commas between
38Exercise
- Trace the following code
-
- for (int i 0 i lt x.size() i)
- Object y x.elementAt(i)
- System.out.println(y.toString())
-
- Is toString needed? Could we just print y?
- We know that the elements are Strings can we
store the result in a String - Review and try in Vector Exercises project
39The Need for Casting
- Suppose we want to store the reference returned
by elementAt to an object of the correct
(specific) type - E.g. String y x.elementAt(i)
- Compiler error ? - why?
- We can use casting
- Specify the data type in parentheses
- E.g. String y (String) x.elementAt(i)
- Again, try in Vector Exercises project
40Wrapper Classes
- Vectors can store objects but not primitives
- What if we want to store integers in a vector?
- Wrapper classes encapsulate primitive values in
objects - Java wrapper classes
- Boolean
- Character
- Integer
- Double
- Have used the class method Integer.parseInt()
41Methods of the Integer Class
- Integer(int n) constructor
- Integer a new Integer(3)
- Integer(String s) constructor
- Integer b new Integer(3)
- int intValue() returns the integer wrapped in
the object - int c a.intValue() // parseInt for String
- Boolean equals(Object obj) returns true if the
"wrapped" integers have the same value - a.equals(b)
42Using Wrapper Classeswith Vectors
- Trace the code
- Integer a new Integer(3)
- Integer b new Integer("3")
- System.out.println(a.equals(b))
-
- int c a.intValue()
- System.out.println("c " c)
- x.addElement(a)
- x.addElement(b)
- System.out.println(x has " x.size() "
elements.") - int d ((Integer) x.elementAt(1)).intValue()
- System.out.println("d " d)
43To the Computers...PreLab 6
- Try drawing your initials by maneuvering the
Turtle around the screen - Linked from course home page
44Java BREAK
45Initializing the Turtle(more on implements soon)
- public class Turtle extends Applet implements
ActionListener - Button leftButton, moveButton, rightButton
- Point startPoint
- Point points
- int direction 0, numPoints 0, stepDist 7
- public void init()
- startPoint new Point(200,200)
- points new Point1000
- resize(400,400)
- leftButton new Button("Left")
- moveButton new Button("Move")
- rightButton new Button("Right")
- add(leftButton)
- add(moveButton)
- add(rightButton)
- leftButton.addActionListener(this)
- moveButton.addActionListener(this)
- rightButton.addActionListener(this)
- // end init method
46Checking Turtle Action
- public void actionPerformed(ActionEvent evt)
- Object btn evt.getSource()
- if (btn leftButton)
- direction (direction3) 4
- if (btn moveButton)
- turtleMove()
- if (btn rightButton)
- direction (direction1) 4
- repaint()
- // end actionPerformed
47turtleMove Method
- private void turtleMove()
- int newX, newY
- if (numPoints 0)
- newX startPoint.x
- newY startPoint.y
- else
- newX pointsnumPoints-1.x
- newY pointsnumPoints-1.y
- switch (direction)
- case 0 newX stepDist break
- case 1 newY stepDist break
- case 2 newX - stepDist break
- case 3 newY - stepDist break
- // end of direction switch
- pointsnumPoints new Point(newX,newY)
- numPoints
- // end turtleMove method
48Turtle paint Method
- public void paint(Graphics g)
- int oldX startPoint.x
- int oldY startPoint.y
- g.setColor(Color.black)
- for (int p0 pltnumPoints p)
- g.drawLine(oldX, oldY, pointsp.x,
pointsp.y) - oldX pointsp.x oldY
pointsp.y - // next point
- g.setColor(Color.green)
- g.fillOval(oldX-5,oldY-5,10,10) // body
- switch (direction) // head
- case 0 g.fillOval(oldX6,oldY-2,4,4)
break - case 1 g.fillOval(oldX-2,oldY6,4,4)
break - case 2 g.fillOval(oldX-10,oldY-2,4,4)
break - case 3 g.fillOval(oldX-2,oldY-10,4,4)
break - // end of switch for head
- // end paint method