Upload
hondafanatics
View
139
Download
0
Tags:
Embed Size (px)
Citation preview
Shlomo Hershkop 2007Shlomo Hershkop 2007 22
Intermediate ReviewIntermediate Review
ReferencesReferences Basic inheritanceBasic inheritance Time classesTime classes Date ClassesDate Classes File input/output File input/output PackagesPackages
Shlomo Hershkop 2007Shlomo Hershkop 2007 33
MemoryMemory
One of the good things about java is that One of the good things about java is that it abstracts memory awayit abstracts memory away
You don’t have to worry about how things You don’t have to worry about how things are being put into memoryare being put into memory
But you still need to be aware of how But you still need to be aware of how things are representedthings are represented
Shlomo Hershkop 2007Shlomo Hershkop 2007 44
Basic ExampleBasic Example
int sum = 100int sum = 100 int arr[];int arr[];
100
X
SUM
arr
Shlomo Hershkop 2007Shlomo Hershkop 2007 55
NextNext
int sum = 100int sum = 100 int arr[];int arr[]; arr = new int[10];arr = new int[10];
100SUM
arr
Shlomo Hershkop 2007Shlomo Hershkop 2007 66
QuestionQuestion
What happens on the last line ?What happens on the last line ? int arr[];int arr[]; arr = new int[10];arr = new int[10]; arr[0] = 12;arr[0] = 12; arr = new int[5];arr = new int[5];
100SUM
arr
Shlomo Hershkop 2007Shlomo Hershkop 2007 77
answeranswer
A new set of ints are allocated and WE A new set of ints are allocated and WE LOSE all data in the old oneLOSE all data in the old one
You need to copy over data (and use a You need to copy over data (and use a temp array)temp array)
Shlomo Hershkop 2007Shlomo Hershkop 2007 88
ReferencesReferences
So a primitive variable is mapped to a location in memorySo a primitive variable is mapped to a location in memory int x; x= 234; int x; x= 234;
Class Objects are a little more complicated since they have member variables and Class Objects are a little more complicated since they have member variables and methodsmethods
Memory references will point to a location which has been setup with the object you Memory references will point to a location which has been setup with the object you createcreate miniVan mycar;miniVan mycar; mycar = new miniVan(….)mycar = new miniVan(….)
234
ref
x
mycarHonda
Odyssey2000Red
Shlomo Hershkop 2007Shlomo Hershkop 2007 99
ReferencesReferences Create new primitive variable y, will result in another memory Create new primitive variable y, will result in another memory
location and value copy location and value copy int y = x;int y = x; Create another miniVan instance in the following will simply make it Create another miniVan instance in the following will simply make it
point to same place (unless new is used)point to same place (unless new is used) miniVan oCar = mycar;miniVan oCar = mycar;
234
234
ref
ref
x
mycarHonda
Odyssey2000Red
y
oCar
Shlomo Hershkop 2007Shlomo Hershkop 2007 1010
Who cares ?Who cares ?
So what is the difference ??So what is the difference ??
Shlomo Hershkop 2007Shlomo Hershkop 2007 1111
Difference !Difference !
Messing with x, won’t affect yMessing with x, won’t affect y
Messing with class reference will change Messing with class reference will change both objectsboth objects
Shlomo Hershkop 2007Shlomo Hershkop 2007 1212
Difference IIDifference II
oCar.year = 2005;oCar.year = 2005; Surprise!Surprise!
234
234
ref
ref
x
mycarHonda
Odyssey2005Red
y
oCar
Shlomo Hershkop 2007Shlomo Hershkop 2007 1313
Why?Why?
If its such a bad idea, why have it at all?If its such a bad idea, why have it at all?
Any ideas why we would want to create Any ideas why we would want to create object using references?object using references?
Shlomo Hershkop 2007Shlomo Hershkop 2007 1414
AdvantageAdvantage
If the class is huge If the class is huge
Don’t want to keep copying all the Don’t want to keep copying all the member variables if I plan on only reading member variables if I plan on only reading it it
Shlomo Hershkop 2007Shlomo Hershkop 2007 1515
Back to ArraysBack to Arrays
Can have array of length 0; Can have array of length 0; not the same as null:not the same as null:
int numbers[];int numbers[]; numbers = new int[0];numbers = new int[0]; numbers = null;numbers = null;
What is the difference here ?What is the difference here ?
Shlomo Hershkop 2007Shlomo Hershkop 2007 1616
Two dimensional arraysTwo dimensional arrays
You can create an array of any You can create an array of any object, including arraysobject, including arrays
Person bunch[] = new Person[10];Person bunch[] = new Person[10]; int[][] table = new int[10][20];int[][] table = new int[10][20]; int t = table[i][j];int t = table[i][j];
An array of an array is a two dimensional arrayAn array of an array is a two dimensional array
Shlomo Hershkop 2007Shlomo Hershkop 2007 1717
Before coding…Before coding…
Before we start to code one last thingBefore we start to code one last thing
How to get user input ??How to get user input ??
Most languages give you access to Most languages give you access to something called STANDARD out/insomething called STANDARD out/in
Shlomo Hershkop 2007Shlomo Hershkop 2007 1818
Standard IN/OUTStandard IN/OUT
Assume there is some way to talk to userAssume there is some way to talk to user
And get user inputAnd get user input
Very low levelVery low level Want something a little higher so don’t have to Want something a little higher so don’t have to
worry for example how they enter the worry for example how they enter the informationinformation In theory could be using hieroglyphics In theory could be using hieroglyphics
Shlomo Hershkop 2007Shlomo Hershkop 2007 1919
Reading Input through scannersReading Input through scanners
Construct ScannerConstruct Scanner from input stream (e.g. System.in)from input stream (e.g. System.in)
Scanner in = new Scanner(System.in)Scanner in = new Scanner(System.in) nextInt, nextDouble reads next int or doublenextInt, nextDouble reads next int or double
int n = in.nextInt();int n = in.nextInt();
hasNextInt, hasNextDouble test whether next token is a hasNextInt, hasNextDouble test whether next token is a numbernumber
next reads next string (delimited by whitespace)next reads next string (delimited by whitespace) nextLine reads next linenextLine reads next line
Shlomo Hershkop 2007Shlomo Hershkop 2007 2020
EclipseEclipse
1.1. Start EclipseStart Eclipse2.2. Start a new project (right click in project Start a new project (right click in project
explorer)explorer)3.3. Double click, right click on default Double click, right click on default
package and start a new classpackage and start a new class4.4. Call it InputTesterCall it InputTester
Check off that you want commentsCheck off that you want comments Check off you want a mainCheck off you want a main
Shlomo Hershkop 2007Shlomo Hershkop 2007 2121
Code then run thisCode then run this
public class InputTesterpublic class InputTester{{ public static void main(String[] args)public static void main(String[] args) {{ Scanner in = new Scanner(System.in);Scanner in = new Scanner(System.in); System.out.print("How old are you?");System.out.print("How old are you?"); int age = in.nextInt();int age = in.nextInt(); age++;age++; System.out.println("Next year, you'll be " + System.out.println("Next year, you'll be " +
age);age); }} }}
Shlomo Hershkop 2007Shlomo Hershkop 2007 2222
codingcoding
Let start to codeLet start to code
Tic tac toe gameTic tac toe game A program to allow two used to play a gameA program to allow two used to play a game
Where to start ??Where to start ?? What objects can you think of ?What objects can you think of ?
Shlomo Hershkop 2007Shlomo Hershkop 2007 2323
Basic parts Basic parts
Board – tic tac toe boardBoard – tic tac toe board What kind of method would you need here ?What kind of method would you need here ? Although it’s a 3 by 3 board, lets keep it generalAlthough it’s a 3 by 3 board, lets keep it general
MoveMove The part which can ask for a move and check if legal and place The part which can ask for a move and check if legal and place
into boardinto board Front endFront end
We would put main in hereWe would put main in here It would start a gameIt would start a game When done ask if you want to play againWhen done ask if you want to play again
Shlomo Hershkop 2007Shlomo Hershkop 2007 2424
Board classBoard class
Would need a constructorWould need a constructor
Reset method to set everything to blankReset method to set everything to blank
Place move to put a move into the boardPlace move to put a move into the board
Print out to see the boardPrint out to see the board
Shlomo Hershkop 2007Shlomo Hershkop 2007 2525
Note pleaseNote please
The users in the game are represented by X’s The users in the game are represented by X’s and O’sand O’s
No reason we can’t use 1,2No reason we can’t use 1,2
If have a member , what does it mean ?If have a member , what does it mean ? public static final int X = 1;public static final int X = 1; public static final int O = 2;public static final int O = 2;
Shlomo Hershkop 2007Shlomo Hershkop 2007 2626
Board.XBoard.X Board.OBoard.O
Don’t need to instantiate to use itDon’t need to instantiate to use it Makes it easier to speak a common Makes it easier to speak a common
language when using the classlanguage when using the class
Shlomo Hershkop 2007Shlomo Hershkop 2007 2727
public class TicTacToe{public class TicTacToe{public static final int EMPTY = 0;public static final int EMPTY = 0;public static final int X = 1;public static final int X = 1;public static final int O = 2;public static final int O = 2;
private final int SIZE = 3; //for 3x3private final int SIZE = 3; //for 3x3
private int[][] board; private int[][] board;
//ok lets add a constructor//ok lets add a constructor
Shlomo Hershkop 2007Shlomo Hershkop 2007 2828
codingcoding
Add constructorAdd constructor
Add reset methodAdd reset method
Add toString methodAdd toString method Use for loopUse for loop Need to translate from 1,2 to X,ONeed to translate from 1,2 to X,O
Don’t hard code values, use your final staticsDon’t hard code values, use your final statics
Shlomo Hershkop 2007Shlomo Hershkop 2007 2929
NextNext
Lets code the move classLets code the move class
Very basicVery basic Need method to get the user’s next moveNeed method to get the user’s next move
Assume move is a move from each userAssume move is a move from each user Need to ask board if game is doneNeed to ask board if game is done
Add another method to the board gameAdd another method to the board game If user enters bad move…what do you want to do ?If user enters bad move…what do you want to do ?
Shlomo Hershkop 2007Shlomo Hershkop 2007 3030
Finally Finally
Now lets code the front end with mainNow lets code the front end with main
Create a class MainGameTTTCreate a class MainGameTTT Have a main in itHave a main in it
What do we need to do next ?What do we need to do next ?
Shlomo Hershkop 2007Shlomo Hershkop 2007 3131
Game logicGame logic
Start a gameStart a game Loop Loop
At the end ask user if they want to play At the end ask user if they want to play another game ?another game ? This is a little tricky to loop….any ideas ?This is a little tricky to loop….any ideas ?
Shlomo Hershkop 2007Shlomo Hershkop 2007 3232
Yay!Yay!
Ok you have a working gameOk you have a working game
Test it out on all your friends Test it out on all your friends
Shlomo Hershkop 2007Shlomo Hershkop 2007 3333
Multiple dimensionsMultiple dimensions
No reason cant create 4,5,6 dimension No reason cant create 4,5,6 dimension arraysarrays
Gets hard to manageGets hard to manage Better idea: Better idea:
Think about another way of representing the Think about another way of representing the datadata
Often creating an object is a better Often creating an object is a better approachapproach
Shlomo Hershkop 2007Shlomo Hershkop 2007 3434
Arrays furtherArrays further
Need to explicitly copy contents of arrays when resizing Need to explicitly copy contents of arrays when resizing arrays with temp onearrays with temp one
Better solution:Better solution: ArrayListArrayList VectorVector
Full object versions of arraysFull object versions of arrays Capacity can grow over timeCapacity can grow over time Useful methods bundles with themUseful methods bundles with them
Shlomo Hershkop 2007Shlomo Hershkop 2007 3535
codecode
Create a new class with a main called VectorTestCreate a new class with a main called VectorTest
Create a vectorCreate a vector
Put in some stuffPut in some stuff Print them outPrint them out Replace something in the middleReplace something in the middle Print it outPrint it out Clear the vectorClear the vector Print it outPrint it out
Shlomo Hershkop 2007Shlomo Hershkop 2007 3636
Default valuesDefault values
Should be aware if you forget to set Should be aware if you forget to set valuesvalues
Might mess up your logicMight mess up your logic Think of multiplying a bunch of numbers and Think of multiplying a bunch of numbers and
not setting one of them…not setting one of them… Compiler/IDE will let you know if you Compiler/IDE will let you know if you
forgot to set values (warning)forgot to set values (warning)