Upload
amber-willis
View
215
Download
0
Embed Size (px)
Citation preview
1
Today’s Objectives
Announcements• The ethics paper is due next week, at the beginning of class• Quiz 1 will be next week, at the beginning of class
– Closed book and closed notes– 15 minutes, approximately nine questions– Ethics – think about the question on slide 44 from WK01.ppt– Definitions – on slides 8 and 13 from WK01.ppt– Five important parts of the software life cycle – slide 25 from WK01.ppt– Java questions – be sure to study counting the iterations of "for" loops;
String operations; instantiating objects; and using an object's methods to assign and to retrieve values
• Homework 1 is posted on the Schedule, due on 14-Feb
Using Java at UHCL – NetBeans IDE Writing a Simple Java Program with NetBeans Basic Java programming
• Classes, objects, and reference variables Bonus Lab 1 – Intro to Java and NetBeans
Week 2
3
Java Versions and Compilers
Sun’s Java 1.5 (JDK 5.0) is the minimum Java version required for the homework
javac• All homework must be compilable on Sun’s version of javac
NetBeans• Recommended IDE• A free IDE available from either NetBeans.org or Sun
Available at:• UHCL Delta Building PC Lab (Delta Bldg., second floor)• Home use
– Download the JDK 5 with NetBeans(NOT the JRE)
– Or download the JDK 5 and NetBeans separately– Macintosh users need to download the J2SE 5 from Apple– See the “Resources” web page for current links
Using Java at UHCL
4
Other IDEs or Compilers
You can use other IDEs or editors, however all homework is required to compile with the version of javac, that is provided with the JDK 5.0 download from Sun
• The TA will check your homework by re-compiling it
• If your program does not compile, you will receive 0 points
• Problems caused by your use of non-compatible compilers or IDEs will not be considered as grounds for grading leniency
Using Java at UHCL
5
Brief Facts About Java
Created by James Gosling at Sun and released in 1995
100% object-oriented Platform independent Versions
• Now at Java SE6 (also known as SE 1.6)• JSE6 was released on 12-Dec-2006
Java Collections Framework– Included with the JDK– Readymade classes for data structures
Brief Facts About Java (Deitel)
Dr. James GoslingFrom eWeek.com, April 14, 2006
6
Filenames
Must be the same as the name of the class in the file
.java• Extension for the Java source code files
.class• Extension for the compiled files
Name of executable file• It’s the name of your class file that contains the main function that
runs your program
Brief Facts About Java (Goodrich, 46)
7
package
The “package” statement defines a series of nested folders where your program files are located
Helps keep the files organized
Goes on the first non-comment, non-space line in the java file
By convention, to guarantee uniqueness, use a reversed domain name, followed by a unique word, all lower case
Place all your code for a particular problem on a homework assignment in the same package, so they’ll be in the same directory
Brief Facts About Java (Goodrich, 46)
package edu.uhcl.sce.hello;
PackageGoes on the firstnon-comment line
The package matches thenested subdirectories
where your code is stored
9
/** * Simple Java Example. */package edu.uhcl.sce.hello;
public class Greeting { private String greeting; public Greeting(String greeting){ this.greeting = greeting; } public String getGreeting(){return greeting;} public void setGreeting(String greeting){ this.greeting = greeting; }}
Simple Java ExampleBasic Java Programming
10
/** * Simple Java Example. */package edu.uhcl.sce.hello;
public class Greeting { private String greeting; public Greeting(String greeting){ this.greeting = greeting; } public String getGreeting(){return greeting;} public void setGreeting(String greeting){ this.greeting = greeting; }}
Simple Java ExampleBasic Java Programming
Comment
Package statement
Constructor initializesthe instance variables
Class name
Public methodto get the data
Instance variable
Public methodto change the data
11
/** * Simple Java Example. */package edu.uhcl.sce.hello;
public class Main { public static void main (String args[]) { Greeting greeting = new Greeting("Hello"); System.out.println(greeting.getGreeting()); }}
Simple Java ExampleBasic Java Programming
12
/** * Simple Java Example. */package edu.uhcl.sce.hello;
public class Main { public static void main (String args[]) { Greeting greeting = new Greeting("Hello"); System.out.println(greeting.getGreeting()); }}
Simple Java ExampleBasic Java Programming
“new” callsthe constructor
Curly bracesaround the class body
“Executable” method
All Java statementsend with a semicolon
Instantiating an object
Printing to the screen
All java code must be within a class
13
The main() function
The entry point for your Java program• Required for a “standalone” program• Usually there’s only one main function per application,
but one main function per class is allowed• Located in a .java source code file, inside a class
The syntaxpublic static void main (String args[])
args[]• An array of arguments passed on the command line• args[0]; //first arg after the command
Basic Java Programming (Goodrich, 18)
14
Compiling and Running fromthe Command Line
Compile with javac
Basic Java Programming
cd to thecorrect directory
All files with the extension .java
Run with javaUse the
correct pathName of the
executable class file
To specify that the current directory is the location of the application classes:
java -classpath . edu.uhcl.sce.hello.Main
15
CLASSPATH
Specification of directories and JAR files• Multiple directories or JARs are separated by ;
When trying to load a class during program execution, Java searches these locations for the class file
Can be specified as:• An operating system environment variable• A setting in an IDE• An option on the command line when running a Java program
from a console window
java -classpath . edu.uhcl.sce.hello.Main
Basic Java Programming (Flanagan, 333)
Name of an executable class
PackageRuns Javaprograms
Specifies that theapplication classes are in the current directory
16
Output and Input
Printing to standard output, usually the screenSystem.out.println("Hello"); //inserts '\n' at end of lineSystem.out.print("Hello"); //no carriage return
Capturing input in a console windowimport java.io.*;public class Main{public static void main(String[] args) { try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a letter: "); String input = br.readLine(); System.out.println("You entered " + input); }catch(IOException e){ System.out.println(e.getMessage()); } }}
Basic Java Programming (Goodrich, 4–5)
18
Software Process
Series of steps for software development• Repeatable procedure—better able to succeed consistently
Our simple process• Phase 1 – Requirements gathering
– What are we making?
• Phase 2 – Analysis and design– How will we build it?
• Phase 3 – Implementation and testing– Build the code for the first version– Get something working, and keep it simple
• Iterations– Start with the core functionality, then add features with
each iteration
Using a Simple Process (Eckel)
19
Phase 1: What are we making?
Problem:• Demonstrate basic Java programming by creating a game
called “Simple Solitaire” that will run in a console window
Requirements:• Simple solitaire is a card game played by one person• Use a regular deck of playing cards• Goal is to discard all of the cards• Shuffle the deck, then deal four cards
1. If two cards have the same rank, discard both2. If two cards have the same suit, discard the lower rank card3. Deal four more cards
Using a Simple Process (Eckel; Drake)
20
Phase 2: How will we build it?Using a Simple Process (Eckel; Drake)
Card
Start by listing all the classes that we need.
• Simple solitaire is a card game played by one person
• Use a regular deck of playing cards
• Goal is to discard all of the cards• Shuffle the deck, then deal four
cards1. If two cards have the same rank,
discard both2. If two cards have the same suit,
discard the lower rank card3. Deal four more cards
Requirements
21
Phase 2: How will we build it?Using a Simple Process (Eckel; Drake)
Card
Deck
Start by listing all the classes that we need.
• Simple solitaire is a card game played by one person
• Use a regular deck of playing cards
• Goal is to discard all of the cards• Shuffle the deck, then deal four
cards1. If two cards have the same rank,
discard both2. If two cards have the same suit,
discard the lower rank card3. Deal four more cards
Requirements
22
Phase 2: How will we build it?Using a Simple Process (Eckel; Drake)
Card
Deck
SimpleSolitaire
Start by listing all the classes that we need.
• Simple solitaire is a card game played by one person
• Use a regular deck of playing cards
• Goal is to discard all of the cards• Shuffle the deck, then deal four
cards1. If two cards have the same rank,
discard both2. If two cards have the same suit,
discard the lower rank card3. Deal four more cards
We need a class for the game itself.
Requirements
23
Phase 2: How will we build it?Using a Simple Process (Eckel; Drake)
Card
Deck
SimpleSolitaire
Main
Start by listing all the classes that we need.
• Simple solitaire is a card game played by one person
• Use a regular deck of playing cards
• Goal is to discard all of the cards• Shuffle the deck, then deal four
cards1. If two cards have the same rank,
discard both2. If two cards have the same suit,
discard the lower rank card3. Deal four more cards
We also need a class for the main() function.
We need a class for the game itself.
Requirements
24
Phase 3: Build the first version
Start programming Get something working Keep it simple – small, simple classes
Using a Simple Process (Eckel; Drake)
26
Objects and Classes
The main pieces in a Java program are objects
In Java, every real object in the problem domain can be represented by an object in the program. Then our program is written to model how these objects interact.
Every object in the program is instantiated from a class that defines the type of data an object can hold and the actions the object can perform
Class – a programming element that contains• “Instance variables” that are related – they may have different
data types• “Methods” – all the operations that can be performed with the
data
Basic Java Programming (Goodrich, 2–4, 47)
27
Defining a ClassBasic Java Programming (Goodrich, 2–4, Drake)
We’ll start by creating a class that we can use to create card objects in the program.
Rank
28
Defining a Class
package edu.uhcl.sce.simplesolitaire;
public class Card{
}
The package statement defines the directory for our files.
Basic Java Programming (Goodrich, 2–4)
Class name, always capitalized
29
Defining a Class
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
}
A class stores its data in instance variables, which are always “private,” for information hiding.
Each card has a rank, which is the number or letter on the face of the card. And each card has a suit, either spades, hearts, diamonds, or clubs.
So the card class must store a value for the rank and the suit of the particular card we want to represent.
Basic Java Programming (Goodrich, 2–4, Drake)
Rank
Spades Hearts Diamonds Clubs
Instance variables can be declared as primitive variables within the class
30
Variables and Data Types
There are eight primitive data types in Javaboolean short floatbyte int doublechar long
Declaring a primitive variable• Allocates storage space in memory• Not automatically initialized unless it is an instance variable
Basic Java Programming (Goodrich, 5)
ij
300030043008
0
value variable namememory address
3012
public class Main { public static void main (String args[]) { int i; //i is declared but not initialized (it’s in main) int j = 0; //j is declared and initialized }}
31
Defining a Class
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
}
Instance variables are automatically initialized to default values.
Basic Java Programming (Goodrich, 2–4, Drake)
Initialized to 0
Rank
Spades Hearts Diamonds Clubs
32
Information Hiding
Instance variables are always made private• The user of an object in your program cannot change the data by
accessing it directly• We can control how we store the data inside the object
– Example: We may decide to store the Suit as a String instead of an int
The user of an object can still get the data and change it, but only by using a public method
• These public methods are often “getters” and “setters”• Method naming convention
– Name starts with “get” if the method returns a value stored in an instance variable of the object
– Name starts with “set” if the method assigns a value to an instance variable in the object
– Name starts with “is” if the method returns a boolean value stored in an instance variable of the object
Basic Java Programming (Goodrich, 15–17)
33
Defining a Class
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
public static final int SPADES = 0; public static final int HEARTS = 1; public static final int DIAMONDS = 2; public static final int CLUBS = 3; public static final int ACE = 1; public static final int JACK = 11; public static final int QUEEN = 12; public static final int KING = 13;}
We define constants that can be used for the suit values and for the ranks of the face cards.
Basic Java Programming (Goodrich, 2–4, Drake)
Rank
Spades Hearts Diamonds Clubs
34
Constants
Use final to declare a constant
Must be initialized with a value when declared, and then its value can never be changed
The name of a constant is usually all caps
If a constant is an instance variable, it should be static
public class MyConstants {public static final double PI = 3.14159;public static final int CAPACITY = 1024;
public static void main (String args[]){ System.out.println("PI = " + MyConstants.PI); }}
Basic Java Programming (Goodrich, 12–13)
35
Assignment Operator
Assignmentint n = 10;
Binary arithmetic operators can be combined with assignment
n += 5; //same as n = n + 5n *= 2; //same as n = n * 2System.out.println("n = " + n); //What prints?
Basic Java Programming (Goodrich, 20–24)
assignment operator
36
Defining a Class
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
public int getRank(){return rank;} public int getSuit(){return suit;} public static final int SPADES = 0; public static final int HEARTS = 1; public static final int DIAMONDS = 2; public static final int CLUBS = 3; public static final int ACE = 1; public static final int JACK = 11; public static final int QUEEN = 12; public static final int KING = 13;}
Basic Java Programming (Goodrich, 2–4, Drake)
Now we can add the methods that describe the operations that can be performed with the data.
For the Card class, we only need to retrieve the values of the data so that we know which card is represented by a particular card object.
Rank
Spades Hearts Diamonds Clubs
37
Methods
Methods are functions that are defined within a class
public int getRank() { return rank; }
Basic Java Programming (Goodrich, 20–24)
methodname
parenthesesare used tocontain all
arguments that arepassed to this method
returnvalue
programstatements arein the method
body
Methods are usually public, which means they can be used in any part of the program where there’s an object of this particular class.
38
Defining a Class
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
public Card(){} public Card(int rank, int suit){ this.rank = rank; this.suit = suit; } public int getRank(){return rank;} public int getSuit(){return suit;} public static final int SPADES = 0; public static final int HEARTS = 1; public static final int DIAMONDS = 2; public static final int CLUBS = 3; public static final int ACE = 1; public static final int JACK = 11; public static final int QUEEN = 12; public static final int KING = 13;}
Basic Java Programming (Goodrich, 2–4, Drake)
A special method, called the “constructor,” is used to create an object of the class
Rank
Spades Hearts Diamonds Clubs
A default constructor that does nothing
Another, overloaded constructor that initializes the instance variables
39
this
The Java keyword “this” is always used to refer to the instance of the current object
In the constructor below, the two assignment statements put an argument’s value into a field in the particular instance of the Card class that is being created
Basic Java Programming (Goodrich, 17–18)
public Card(int rank, int suit){ this.rank = rank; this.suit = suit;}
A reference to the current object
“Dot”operator
Name of the instancevariable
40
Constructor
Public member function with the same name as the class and with no return value
• When an object is instantiated, the constructor is automatically called to initialize the instance variables
• A class can have more than one overloaded constructor, as long as the arguments are different for each
• The default constructor has no arguments; default values are assigned public Person(){
this.name = "Adam"; this.ID = 0;
}
• Arguments can be used to set the values stored in the object public Person( String name, int ID)
this.name = name; this.ID = ID;
}
Basic Java Programming (Goodrich, 17–18)
41
Using a ClassTo instantiate an object
After a class has been defined, it creates a new data type
We can use it to “declare a variable,” but we use a different terminology. We say that a class is used to create an “object” that is an instance of the class.
Instantiating an objectpublic static void main(String args[]){ Card aceOfSpades = new Card(Card.ACE,Card.SPADES);}
Name of the objectName of the
class
Basic Java Programming (Goodrich, 7)
Allocate memory andcall the constructor
42
Reference Variables
The variables that represent objects are called "reference variables"
The reference variable contains the address of the memory allocated by new
Objects and Classes (Goodrich, 7)
public static void main(String args[]){ Card aceOfSpades = new Card(Card.ACE,Card.SPADES);}
Name of the objectis called a
"reference variable"
new allocatesmemory and returns
its address
43
Reference Variables
We can say that the memory address contained in a reference variable “points” to the memory allocated by new for storing the object
Basic Java Programming
ij
300030043008
0
value variable namememory address
3012aceOfSpades4096
4096 10
public static void main(String args[]){ Card aceOfSpades = new Card(Card.ACE,Card.SPADES);}
ranksuit
(Remember, this constant is 1, and this constant is 0)
44
public class Main{ public static void main(String args[]){ Card aceOfSpades = new Card(Card.ACE,Card.SPADES); System.out.println(aceOfSpades.getRank()); }
}
Using an ObjectTo call the methods
All of the operations that an object can perform are defined by its public methods
Java programs consist of objects and the method calls of those objects
Object “Dot”operator
Methodcall
Parentheses are required
Basic Java Programming (Goodrich, 15–17)
To invoke a method, we must use an object. We cannot simply write the method name in a line of code (as in C).
46
Class String
Java uses an object-oriented approach to strings with the String class
Creating a String objectString s1 = "Go Dog";String s2 = "Madam, I'm Adam";
String objects have many useful methods
• Getting the length of a String objectint len = s1.length(); //returns 6
Basic Java Programming (Goodrich, 8–9, 540; Flanagan, 491–495)
Object “Dot”operator
Methodcall
Parentheses are required
47
Class String
Accessing individual charsString s1 = "Go Dog";
System.out.print(s1.charAt(5));//What prints?
Accessing all chars in a String, one at a time
Basic Java Programming (Goodrich, 8–9, 540; Flanagan, 491–495)
What prints?
String s1 = "Go Dog";for( int i=0; i<s1.length(); ++i ){ System.out.println( s1.charAt(i) );}
48
Increment and Decrement
Post-increment operatorint n = 10;n++; //returns n then adds 1 to it
Pre-increment operatorint n = 10;++n; //adds 1 to n then returns it
Post-decrement operatorint n = 10;n--; //returns n then subtracts 1 from it
Pre-decrement operatorint n = 10;--n; //subtracts 1 from n then returns it
Basic Java Programming (Goodrich, 22)
49
Iterative Control Structure
Looping with for
for( int i=0; i<10; ++i ){ System.out.print( i + " ");}
Basic Java Programming (Goodrich, 30–31)
50
Iterative Control Structure
Looping with for
for( int i=0; i<10; ++i ){ System.out.print( i + " ");}
Initialization – assigns the starting value and is executed once.
Condition – tested at the beginning of each loop, and the loop is executed only if it evaluates to true.
Expression – evaluated at the end of each loop
Block of statements executed in
the loop
Basic Java Programming (Goodrich, 30–31)
51
A block is needed only if multiple statements are executed in each loop.
for( int i=0; i<10; ++i ){ System.out.print(i); System.out.print(" ");}
for Loop
If only one statement is executed in each loop, it’s not necessary to define a
block with { and }.
for( int i=0; i<10; ++i ) System.out.print(i+" ");
Basic Java Programming (Goodrich, 26–27)
52
Changes to the Value of i
for( int i=0; i<5; ++i ){ System.out.print(i + " ");}
i = i + 14Fifth loop
i = i + 13Fourth loop
i = i + 12Third loop
1
0 (starting value)
Value of iduring the loop
i = i + 1Second loop
i = i + 1First loop
Expression at the end of the loopIteration
Basic Java Programming (Goodrich, 30–31)
53
Nested for Loop
int result = 0;for( int i=0; i<3; ++i ) for( int j=0; j<5; ++j ) ++result;
1542
1432
1322
1212
1102
1041
931
821
711
601
540
430
320
1
0
j
20
10
resulti
Basic Java Programming (Goodrich, 30–31)
54
Nested Loop with Dependent Variable
int result = 0;for( int i=0; i<3; ++i ) for( int j=i; j<5; ++j ) ++result;
1242
1132
1022
941
831
721
611
540
430
320
1
0
j
20
10
resulti
Basic Java Programming (Goodrich, 30–31)
55
How many iterations?
for( int i=0; i<10; ++i ) System.out.print(i + " ");
for( int i=10; i>0; --i ) System.out.print(i + " ");
int result = 0;for( int i=0; i<2; ++i ) for( int j=0; j<3; ++j ) ++result;
Basic Java Programming
57
Equality Operators andRelational Operators
Equality operators• equality operator == (don’t confuse with = )
x == y; //x is equal to y• operator !=
x != y; //x is not equal to y
Relational operators• operator <
x < y; //x is less than y• operator >
x > y; //x is greater than y• operator <=
x <= y; //x is less than or equal to y• operator >=
x >= y; //x is greater than or equal to y
Basic Java Programming (Goodrich, 22)
58
Conditional Control Structures
Select from different actions, depending on whether a condition is true
Basic Java Programming (Goodrich, 27)
public class Main{ public static void main(String args[]){ int courseScore = 89; String courseGrade;
if (courseScore >= 91) courseGrade = "A"; else if (courseScore >= 89) courseGrade = "A-"; else courseGrade = "B";
System.out.println(courseGrade); }}
If the condition in parentheses is true, then the following line of code will be executed
An if statement can be followed by an “else if” or an “else”
59
equals
Objects must be compared with equals
Java Strings should be compared with either equals or equalsIgnoreCase
String s1 = "Hello, ", s2 = "World";if( s1.equals(s2) ) System.out.println("equal");else System.out.println("not equal");
Basic Java Programming (Goodrich, 8–9, 540; Flanagan, 491–495)
60
equals
When two reference variables are compared with == Java returns true only if both references contain the same memory address; usually that’s not what we want
Usually, two objects will be equal when they contain the same values in their instance variables
Objects must be compared with equals
Default version of equals• Available to all Java objects• Works like ==
Your classes should override equals so that it compares the values stored in the objects which are being compared
Basic Java Programming (Goodrich, 8–9, 540; Flanagan, 491–495)
61
Override equals in Card
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
public boolean equals(Object that){ Card thatCard = (Card)that; return (rank == thatCard.rank) && (suit == thatCard.suit); }
//...}
One Card object is equal to another when the values in their rank and suit fields are equal.
Rank
Spades Hearts Diamonds Clubs
Basic Java Programming (Goodrich, 8–9, 540; Flanagan; Drake)
if (card1.equals( card2 )) System.out.println("equal");else System.out.println("not equal");
62
Override equals in Card
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
public boolean equals(Object that){ if (this == that){ return true; } Card thatCard = (Card)that; return (rank == thatCard.rank) && (suit == thatCard.suit); }
//...}
One Card object is equal to another when the values in their rank and suit fields are equal.
An object is always equal to itself.
Rank
Spades Hearts Diamonds Clubs
Basic Java Programming (Goodrich, 8–9, 540; Flanagan; Drake)
63
Override equals in Card
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
public boolean equals(Object that){ if (this == that){ return true; } if (that == null){ return false; } Card thatCard = (Card)that; return (rank == thatCard.rank) && (suit == thatCard.suit); }
//...}
One Card object is equal to another when the values in their rank and suit fields are equal.
An Card object is always equal to itself.
A Card object is never equal to a null reference.
Rank
Spades Hearts Diamonds Clubs
Basic Java Programming (Goodrich, 8–9, 540; Flanagan; Drake)
64
Override equals in Card
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
public boolean equals(Object that){ if (this == that){ return true; } if (that == null){ return false; } if (getClass() != that.getClass()){ return false; } Card thatCard = (Card)that; return (rank == thatCard.rank) && (suit == thatCard.suit); }
//...}
One Card object is equal to another when the values in their rank and suit fields are equal.
An Card object is always equal to itself.
A Card object is never equal to a null reference.
A Card object is never equal to an object of a different class.
Rank
Spades Hearts Diamonds Clubs
Basic Java Programming (Goodrich, 8–9, 540; Flanagan; Drake)
65
More String Methods
Java Strings can be concatenated with +String s1 = "Go dog";System.out.println("Length " + s1.length());
Other operationss1 = s1.toUpperCase();s = s.replaceAll(",","");s = s.replaceAll(" ","");if ( Character.isLetter(s1.charAt(5) )){ System.out.println("letter");}
Basic Java Programming (Goodrich, 8–9, 540; Flanagan, 491–495)
66
Class StringBuilder
String objects are immutable• They cannot change• To change a String object, new memory is re-allocated behind
the scenes
Use a StringBuilder object instead of a String when text must be processedStringBuilder sb = new StringBuilder();String s2 = "Madam, I'm Adam";for( int i=0; i<s2.length(); ++i ){ if ( Character.isLetter(s2.charAt(i) )){ sb.append(s2.charAt(i)); }}
Getting a String object from a StringBuilder objectString s3 = sb.toString();
Basic Java Programming (Goodrich, 9, 540; Flanagan, 495–497)
67
toString
An object can be converted to a String with a builtin method named toString
System.out.println automatically calls the toString method of objects that are passed to it
When an object that is not a String is concatenated with a String using operator +, its toString method is used to convert the object
Card myCard = new Card(Card.ACE,Card.SPADES);System.out.println("myCard = " + myCard);
Your classes should override the default toString
Basic Java Programming (Flanagan, 34)
68
Override toString in Card
package edu.uhcl.sce.simplesolitaire;
public class Card{ private int rank; private int suit;
public String toString(){ return "" + "-A23456789TJQK".charAt(rank) + "shdc".charAt(suit); }
//...
public static final int SPADES = 0; public static final int HEARTS = 1; public static final int DIAMONDS = 2; public static final int CLUBS = 3; public static final int ACE = 1; public static final int JACK = 11; public static final int QUEEN = 12; public static final int KING = 13;}
When a Card object is printed, the output should display the values in the rank and suit fields.
Rank
Spades Hearts Diamonds Clubs
Basic Java Programming (Flanagan; Drake)
Card aceOfSpades = new Card(Card.ACE,Card.SPADES);System.out.println(aceOfSpades);
This code prints this output.
As
69
UML Class Diagram
Card
– rank : int– suit : int
+ Card()+ Card(rank : int, suit : int)+ getRank() : int+ getSuit() : int
public class Card { private int rank; private int suit; public Card(){} public Card(int rank, int suit){ this.rank = rank; this.suit = suit; } public int getRank(){ return rank; } public int getSuit(){return suit;}}
Class name(The top section)
Scopeprivatepublic
Instance variables are in the middle section.Methods are in the bottom section.
Datatype of an instance variable
Argumentname
Returndatatype
Data type ofthe argument
Basic Java Programming
70
Where is the error?
package edu.uhcl.edu.errorsample;
public class Main{ public static void main(String args[]){ Person admin; admin.setName("Bob"); }}
Basic Java Programming
71
Where is the error?
package edu.uhcl.edu.errorsample;
public class Main{ public static void main(String args[]){ Person admin; admin.setName("Bob"); }}
Basic Java Programming
ERROR! No memory allocated//CorrectionPerson admin = new Person();
74
Bonus Labs
Optional, guided lab assignment• 2–4 scheduled during the semester• During regular class time, but at the end of the period• Simple assignments that will give you some hands-on Java experience
Procedure• For some labs, I’ll do a demo first (usually as an earlier part of the lecture)• Then you can complete the assignment on your own• Print it and hand it in before the end of class
Rules• Do your own work, but you may help each other• You may ask the instructor for help• You may leave if you finish early or if you do not wish to do this
assignment
1 bonus point added to a quiz grade for each lab correctly completed and handed in before the end of class
Bonus Lab
75
References
Davison, Andrew, Killer Game Programming in Java. Sebastopol, CA:O'Reilly Media, Inc., 2005.
Deitel, H. M. and P. J. Deitel, Java How to Program. Upper Saddle River, NJ: Prentice Hall.
Drake, Peter, Data Structures and Algorithms in Java. Upper Saddle River, NJ: Pearson Prentice Hall, 2006.
Eckel, B., Thinking in C++, Second Edition. Upper Saddle River, NJ: Prentice Hall, 2002.
Flanagan, D., Java in a Nutshell, 5th Edition. Sebastopol, CA:O'Reilly Media Inc., 2005.
Goodrich, M. T. and R. Tamassia, Data Structures and Algorithms in Java. Hoboken, NJ: John Wiley & Sons, Inc., 2006.