intermediate review

37
Shlomo Hershkop Shlomo Hershkop 2007 2007 1 Intermediate Review Intermediate Review

Upload: tim

Post on 12-Jan-2016

42 views

Category:

Documents


0 download

DESCRIPTION

Intermediate Review. Intermediate Review. References Basic inheritance Time classes Date Classes File input/output Packages. Memory. One of the good things about java is that it abstracts memory away You don’t have to worry about how things are being put into memory - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 11

Intermediate ReviewIntermediate Review

Page 2: Intermediate Review

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

Page 3: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 33

MemoryMemory

One of the good things about java is One of the good things about java is that it abstracts memory awaythat it abstracts memory away

You don’t have to worry about how You don’t have to worry about how things are being put into memorythings are 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

Page 4: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 44

Basic ExampleBasic Example

int sum = 100int sum = 100 int arr[];int arr[];

100

X

SUM

arr

Page 5: Intermediate Review

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

Page 6: Intermediate Review

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

Page 7: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 77

answeranswer

A new set of ints are allocated and A new set of ints are allocated and WE LOSE all data in the old oneWE LOSE all data in the old one

You need to copy over data (and use You need to copy over data (and use a temp array)a temp array)

Page 8: Intermediate Review

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 Class Objects are a little more complicated since they have member variables and methodsvariables and methods

Memory references will point to a location which has been setup with the Memory references will point to a location which has been setup with the object you createobject you create

miniVan mycar;miniVan mycar; mycar = new miniVan(….)mycar = new miniVan(….)

234

ref

x

mycarHondaOdyssey2000Red

Page 9: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 99

ReferencesReferences Create new primitive variable y, will result in another Create new primitive variable y, will result in another

memory location and value copy memory location and value copy int y = x;int y = x; Create another miniVan instance in the following will simply Create another miniVan instance in the following will simply

make it point to same place (unless new is used)make it point to same place (unless new is used) miniVan oCar = mycar;miniVan oCar = mycar;

234

234

ref

ref

x

mycarHondaOdyssey2000Red

y

oCar

Page 10: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 1010

Who cares ?Who cares ?

So what is the difference ??So what is the difference ??

Page 11: Intermediate Review

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 Messing with class reference will change both objectschange both objects

Page 12: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 1212

Difference IIDifference II

oCar.year = 2005;oCar.year = 2005; Surprise!Surprise!

234

234

ref

ref

x

mycarHondaOdyssey2005Red

y

oCar

Page 13: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 1313

Why?Why?

If its such a bad idea, why have it at If its such a bad idea, why have it at all?all?

Any ideas why we would want to Any ideas why we would want to create object using references?create object using references?

Page 14: Intermediate Review

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 member variables if I plan on only reading it reading it

Page 15: Intermediate Review

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 ?

Page 16: Intermediate Review

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 An array of an array is a two dimensional arrayarray

Page 17: Intermediate Review

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

Page 18: Intermediate Review

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 Want something a little higher so don’t

have to worry for example how they enter have to worry for example how they enter the informationthe information In theory could be using hieroglyphics In theory could be using hieroglyphics

Page 19: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 1919

Reading Input through Reading Input through scannersscanners

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 hasNextInt, hasNextDouble test whether next token is a numbertoken is a number

next reads next string (delimited by whitespace)next reads next string (delimited by whitespace) nextLine reads next linenextLine reads next line

Page 20: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 2020

EclipseEclipse

1.1. Start EclipseStart Eclipse2.2. Start a new project (right click in Start a new project (right click in

project explorer)project 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

1.1. Check off that you want commentsCheck off that you want comments2.2. Check off you want a mainCheck off you want a main

Page 21: Intermediate Review

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); }} }}

Page 22: Intermediate Review

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 A program to allow two used to play a

gamegame

Where to start ??Where to start ?? What objects can you think of ?What objects can you think of ?

Page 23: Intermediate Review

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 The part which can ask for a move and check if legal and

place into boardplace into 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

Page 24: Intermediate Review

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

Page 25: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 2525

Note pleaseNote please

The users in the game are represented by The users in the game are represented by X’s and O’sX’s and 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;

Page 26: Intermediate Review

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

Page 27: Intermediate Review

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

Page 28: Intermediate Review

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

Page 29: Intermediate Review

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 If user enters bad move…what do you want to

do ?do ?

Page 30: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 3030

Finally Finally

Now lets code the front end with Now lets code the front end with mainmain

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 ?

Page 31: Intermediate Review

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 At the end ask user if they want to play another game ?play another game ? This is a little tricky to loop….any ideas ?This is a little tricky to loop….any ideas ?

Page 32: Intermediate Review

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

Page 33: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 3333

Multiple dimensionsMultiple dimensions

No reason cant create 4,5,6 No reason cant create 4,5,6 dimension arraysdimension arrays

Gets hard to manageGets hard to manage Better idea: Better idea:

Think about another way of representing Think about another way of representing the datathe data

Often creating an object is a better Often creating an object is a better approachapproach

Page 34: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 3434

Arrays furtherArrays further

Need to explicitly copy contents of arrays when Need to explicitly copy contents of arrays when resizing arrays with temp oneresizing arrays 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

Page 35: Intermediate Review

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

Page 36: Intermediate Review

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 Think of multiplying a bunch of numbers

and not setting one of them…and 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)

Page 37: Intermediate Review

Shlomo Hershkop 2007Shlomo Hershkop 2007 3737

Hope you had fun learning this!Hope you had fun learning this!