Title: Lecture 5 Outline
1Lecture 5 Outline
- Project
- Arrays
- Full example class and objects
2Project
- BOSS submit - end date
- Ignore message not registered
- Automated marking so your output needs to be
exactly as stated - else your program will fail
the checks - Must compile else score 0
- E.g
- Exercise 2 Write a program called
MultiplesOfThree that will calculate the first n
multiples of 3. You should ask the user to input
how many multiples (i.e. n) they want to display
on screen. - An example of the expected output is
- How Many Numbers? 4
- Check your file name MultiplesOfThree case
sensitive - Submit only java files .java
- Check you give the correct command line arguments
your program needs to be able to handle them
correctly
3Command line arguments
- Public static void main(String args)
- Int a Integer.parseInt(args0)
- String - array starts0 java
- Int a Integer.parseInt(args0)
Use in your program
4Arrays
5Lecture Goals
- Revise arrays and two-dimensional arrays
- Work through a full example - designing classes
and objects
Continued
6What is an Array
- one-dimensional arrays
- An array has a fixed number of elements and all
elements are of the same type - Each box has an index which in java and C
starts with 0 - Here is an array which holds the ages of 10
people
0 1 2 3 4
5 6 7 8 9
32 34 56 32 12 67
21 34 21 45
7Arrays
- Array Sequence of values of the same type
- Construct array
- Store in variable of type double
new double10
double data new double10
Continued
8Arrays
- When array is created, all values are initialized
depending on array type - Numbers 0
- Boolean false
- Object References null
9Arrays
Figure 1An Array Reference and an Array
10Arrays
data2 29.95
Figure 2Storing a Value in an Array
11Arrays
- Using the value stored
- Get array length as data.length.
- Index values range from 0 to length - 1
System.out.println("The value of this data item
is " data4)
Continued
12Arrays
- Accessing a nonexistent element results in a
bounds error - Limitation Arrays have fixed length
double data new double10data10 29.95
// ERROR
13Syntax Array Construction
 new typeNamelength Example  new
double10 Purpose To construct an array with a
given number of elements
14Syntax Array Element Access
arrayReferenceindex Example  data2 Purpose
To access an element in an array
15(No Transcript)
16(No Transcript)
17(No Transcript)
18(No Transcript)
19 20(No Transcript)
21(No Transcript)
22(No Transcript)
23(No Transcript)
24(No Transcript)
25(No Transcript)
26Lab
- Example SortTest.java
- Using arrays in sorting technique
27- public class SortTest
- /
- sort - sorts the values in the array x
into ascending order -
- /
- public static void sort(double x)
-
- int i,j
- double temp
-
- for (ix.length-1 igt0 i--)
-
- for (j0 jlti j)
-
- if (xjgtxj1) // swap
round if out of order - tempxj
- xjxj1
J j1 3 2 Temp 3
J j1 2 Temp 3
J j1 2 Temp 3
28/ main - tester for the method sort /
public static void main(String args)
int i,n double b
// Enter data used for testing MaInput
Manew MaInput() nMa.readInt("How many
numbers") // now when we know how many
numbers we want to sort // allocate the
memory bnew doublen // read the
data for (i0 iltn i)
biMa.readDouble("number "(i1)" ")
// Call the sort methods sort(b)
System.out.println("gt After sort - numbers
sorted lt") // Print the sorted array
for (i0 iltn i)
System.out.println("number "(i1)" "bi)
// End of the class
SortTest
29Two-Dimensional Arrays
- When constructing a two-dimensional array, you
specify how many rows and columns you need - You access elements with an index pair aij
final int ROWS 3final int COLUMNS
3String board new StringROWSCOLUMNS
boardij "x"
30A Tic-Tac-Toe Board
Figure 6A Tic-Tac-Toe Board
31Traversing Two-Dimensional Arrays
- It is common to use two nested loops when filling
or searching
for (int i 0 i lt ROWS i) for (int j 0
j lt COLUMNS j) boardij " "
32File TicTacToe.java
01 / 02 A 3 x 3 tic-tac-toe board. 03
/ 04 public class TicTacToe 05 06
/ 07 Constructs an empty board. 08
/ 09 public TicTacToe() 10 11
board new StringROWSCOLUMNS 12 //
Fill with spaces 13 for (int i 0 i lt
ROWS i) 14 for (int j 0 j lt
COLUMNS j) 15 boardij "
" 16 17
Continued
33File TicTacToe.java
18 / 19 Sets a field in the board.
The field must be unoccupied. 20 _at_param i
the row index 21 _at_param j the column
index 22 _at_param player the player ("x" or
"o") 23 / 24 public void set(int i, int
j, String player) 25 26 if
(boardij.equals(" ")) 27
boardij player 28 29 30
/ 31 Creates a string representation of
the board, such as 32 x o 33
x 34 o 35 _at_return the string
representation 36 /
Continued
34Full example how to plan a program
- Noughts and Crosses
- Tick-tac-toe
- Look at building classes
- How to use Objects
- Difference between instance and class
variables/methods - 2-dimensional arrays
35The game Noughts and Crosses
- The Game problem definition
- Two players
- 3 by 3 board of squares
- One player crosses (X) , other noughts (O)
- Players take turns in placing a nought or cross
in one of the nine squares - A player wins if they have three of their pieces
- Placed horizontally, diagonally or vertically
36Planning a solution
- The problem definition broken down into parts
- Part 1 a 3-by-3 noughts and crosses board
- Part 2 two players
- Part 3 the game
- We can use Objects and Classes in Java to
represent this problem/game
37But how?
- The board
- Represent board as 2- dimensional array
- Define the board class
- Define the methods associated with board class
- Instance methods for Board class, class methods
for Board class - Defining what is a winner
38The board
- The board contains
- A 3-by-3 set of squares
- Each square can contain a nought, a cross, or a
blank - Each square needs to be updateable (move)
39Representing the board using a 2-dimensional
array
- Assume the noughts and crosses are chars
- Char cross X
- Char nought O
- Char blank
- The board consists of an array of columns
- And is an array of rows
- Char board new charROWSCOLUMNS
- Char board new char33
40The board as 2-dimensional array
- This data is encapsulated in a board class
- Should the data belong to an instance or to the
class itself?
41- Lets remind ourselves of instance variables and
class variables
42Remember instance variables
- An object of a class is also referred to as an
instance of that class - When you create an object the object will contain
all the variables that were included in the class
definition.
43- However the variables in a class definition are
not all the same there are two kinds - One kind of variable is associated with each
object uniquely each instance of the class will
have its own copy of each of these variables ,
with its own value assigned. - These differentiate one object from another,
giving an object its individuality name,
address, telephone number Person class. These are
referred to as instance variables
44Remember Static fields / class fields
- 2) The other kind of class variable is associated
with the class and is shared by all objects of
the class. - There is only one copy of each of these kinds of
variables no matter how many class objects are
created - and they exist even if no objects have been
created
45- Called class variable because variable belongs to
class. - or called static because used with
static keyword - They can be referenced by any object or class
- If the value of a class variable is changed then
the new value is available in all the objects of
that class. -
- This is different from the instance variables
where changing a value for one object does not
affect the values in other objects
46Shared between all objects Sphere.PI
Class Sphere Definition --------------------------
------ Public class Sphere // class
variable Static double PI3.14 //instance
variables double xCenter double xCenter double
xCenter double xCenter
3.14
globe xCenter yCenter zCenter radius
Sphere Objects
- Ball
- xCenter
- yCenter
- aCenter
- radius
Each object gets its own copy
47Access modifiers in Java
48 49The board as 2-dimensional array
- This data is encapsulated in a board class
- Should the data belong to an instance or to the
class itself? - Static data - belongs to the class
- Non-static data - belongs each instance of
the class - Os and Xs ?
- Will be the same for each instance of the game,
so they should be class based - The board array?
- Is different for each instance of the game, so
should be object (or instance) based
50The Board Class
- Class Board
-
- private static char cross X
//class variables - private static char nought O
- private static char blank
- private char board new char 33
//instance variable - Board()
-
- for (inti0 Iltboard.lenghtj) //for
each row - for (int j 0 jltboard0.lenghtJ)
//for each column - boardijblank
-
-
51Methods for the Board class
- Instance methods for the board class
- Printing the board (accessor/get method)
- public void printBoard() // INSTANCE METHOD
-
- System.outprintln()
- for int(i0 I lt board.length i) //
for each row -
- for (int j 0 jltboard0.length j)
- System.out.print( boardij
) - System.out.println()
-
- System.out.println()
-
- This is an instance method, it is non-static,
because the data that we are getting is
non-static
52Class methods for Board class
- Public static void setCross (char c)
- cross c
- Public static void setNought (char c)
- nought c
- Public static void setBlank (char c)
- blank c
- Using the methods
- instance methods boardObject.printBoard()
- Class methods Board.setBlank( )
-
- Static methods do not operate on an object but
they are still defined inside the class
Why? because data is static
Prefix with name of the instance of the object
Prefix with name of class
53Detecting a winning move
- Add a data field which states whether a game has
been won - private boolean winner
- This is a non-static, as the win is associated
with a particular instance of the board - Set it to false in the constrcutor method
- Winner false
- Add a (non-static) method to access data field
- Public boolean isWinner()
-
- winner detectWinner() //to be defined..
- Return winner
-
54Defining a winner
- A winning move is one in which
- A row is completed with all noughts and crosses
- A column is completed with all noughts and
crosses - A diagonal is completed with all noughts and
crosses - private boolean detect()
-
- if (rowWinner() columnWinner()
diagonalWinner()) - Return true
- Else return false
-
55- private boolean rowWinner()
-
- for (int 0 iltboard.length i) //for
each row - if ((boardi0 boardi1)(boardi1
boardi2)) - if (boardi0!blank) return true
- return false
-
- private boolean columnWinner()
-
- for (int 0 iltboard.length i) //for each
column - if ((board0i board1i)(board1i
board2i)) - if (board0i!blank) return true
- return false
-
- private boolean diagonalWinner()
- If((board00board11(board11board
22)) - if (board00!blank) return true
- If((board02board11(board11board
20))
56(No Transcript)