Download Weeks 1-3 notes

Document related concepts
no text concepts found
Transcript
CPSC150
Fall 2005
Dr. L Lambert
Java
Dr. L. Lambert
CPSC150
Week 1
Chapter 1
Java, BlueJ, Objects, Terms
Java
Dr. L. Lambert
CPSC150
Syllabus







Java
Java
CPSC150Lab
Attendance, but does not count
weekly quiz. Due the next week. Graded.
Collaborative. Come prepared to work on it in class.
Come see me/Java expert early and often
Ask questions
Consult with (possibly non-expert) peers, but be
careful. >50% of your grade is exams.
Dr. L. Lambert
CPSC150
Quiz: week 1





Java
Using the Shapes example, draw a snowman
in BlueJ (by creating objects and modifying
them) that looks like this (exact dimensions
and placement are not important).
Capture the image and window with the
object bench (yours will not be empty as this
one is)
Print source code for one Class (e.g., Circle)
Identify in these three at least one of each
of the following: object, Class, method call,
parameter, instance, method (definition),
signature, type, source code, return value
Turn in a printed copy of: captured image,
captured BlueJ window, source code for one
Class. Terms should be identified on each as
appropriate.
Dr. L. Lambert
CPSC150
Virtual Machine

Review:




Java developed to be platform independent


Java
Computers understand machine language only
Each computer has its own language
No computer understands English, Powerpoint, or Java
Virtual machine built on top of each actual machine to make
all machines (windows, mac, UNIX) look alike
Java compiles to byte-code – not machine code, but “virtual
machine code”
Dr. L. Lambert
CPSC150
Why Java?





Java
Java is a large, complete language
Works well with web applications
GUIs “part” of the language
Extensive libraries
(Other CS courses will cover C++)
Dr. L. Lambert
CPSC150
Why BlueJ







Java
Easy to use
Object-oriented
Start programming immediately
GUI, not console-based
Object visualization using UML
Debugger, Editor, other standard stuff
Simple, not for advanced applications
Dr. L. Lambert
CPSC150
Using Java and BlueJ








Java
We will use BlueJ for program development
BlueJ runs on the Java virtual machine
BlueJ is IDE – lots of others (e.g., Eclipse)
BlueJ is free and available for Mac, Windows, UNIX
You will test and submit program using UNIX
Use your Hunter Creech Account
Download BlueJ for your home machines for
development: www.bluej.org
(download Java 1.5 first):
http://java.sun.com/j2se/1.5.0/download.jsp
(Download SDK, NOT JRE)
Dr. L. Lambert
CPSC150
Looking at an Example:
External View
• UseBlueJ
• on Suns in Hunter Creech
• on Macs in G115
• on your own computer
• (programs submitted on UNIX/Hunter Creech
accounts)
• Demo: Shapes – bluej import, compile
• Terms:
• object (on object bench and in source code), class, instance, method
(definition), method call, return value, parameter, source code, signature (in
source code and external view), formal parameter, actual parameter, type
• cp /usr/local/examples/shapes .
Java
Dr. L. Lambert
(dot MUST be there)
CPSC150
Reading and Writing
Java Code
Weeks 1 and 2
Chapters 1 and 2
Java
Dr. L. Lambert
CPSC150
Quiz: week 2
(= you know enough to do Quiz 1)



Print Picture.java from the BlueJ examples folder.
On that paper, write by hand (don’t type) exercises 1.13 and
1.14, page 12.
Add by hand three methods:




Java
in Picture.java, write addWindow that adds a window to the other side
of the house (estimate where it would be, or code it, then write it down).
in Circle.java, write a constructor that takes two ints and sets the
Xposition field to the first and the Yposition field to the second
in Circle.java, write an accessor method getSize that returns the value
of diameter
in Circle.java, write a mutator method setPosition that takes two int
parameters that represent the new x and y position of the circle. If x >=
0 and <= 300 and y >= 0 and <= 300, change XPosition and YPosition
to be the values in the parameters and redraw the Circle. Otherwise, do
nothing. Start this by coding it without the if.
Dr. L. Lambert
CPSC150
Review

External View

In BlueJ main window,
Classes
 Object bench
 Class relationships
 Create Objects
 Call/Invoke Methods of objects

Java
Dr. L. Lambert
CPSC150
Source Code (Internal View)


import
Comments // single line
/* */ multiline
/**
*/ Javadoc
Class definitions
public class Picture
{
// fields
// constructors
// methods
}

Java
Dr. L. Lambert
CPSC150
Class details:
fields/instance variables

Lifetime/scope of class


private int myfield; // primitive



char, boolean, double, a few others
private String mystring; // class
private Circle sun;


field vs local variable
user and library defined
BlueJ: primitive has data; object has pointer
Clock example, ClockDisplay, NumberDisplay
(Inspect object in
/home/lambert/Public/projects/chapter03/clock-display)

Java
Dr. L. Lambert
CPSC150
Source Code (Internal View)


import
Comments // single line
/* */ multiline
/**
*/ Javadoc
Class definitions
public class Picture
{
// fields
// constructors
// methods
}

Java
Dr. L. Lambert
CPSC150
Class details: constructors



Initialize objects. Called when object is created
no return type
can be overloaded
public Circle( )
public Circle(int d, int x, int y, color c)
{ // give fields default values
{ // give fields client-specified values
diameter = 30;
diameter = d;
xPosition = 20;
xPosition = x;
yPosition = 60;
yPosition = y;
color = "blue";
color = c;
isVisible = false;
isVisible = false;
}
}
Java
Dr. L. Lambert
CPSC150
Work on Quiz Time



Print Picture.java from the BlueJ examples folder.
On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12.
Add by hand three methods:
 in Picture.java, write addWindow that adds a window to the other
side of the house (estimate where it would be, or code it, then write
it down).



Java
in Circle.java, write a constructor that takes two
ints and sets the Xposition field to the first and
the Yposition field to the second
in Circle.java, write an accessor method getSize that returns the value of
diameter
in Circle.java, write a mutator method setPosition that takes two int parameters
that represent the new x and y position of the circle. If x >= 0 and <= 300 and y
>= 0 and <= 300, change XPosition and YPosition to be the values in the
parameters and redraw the Circle. Otherwise, do nothing. Start this by coding it
without the if.
Dr. L. Lambert
CPSC150
Source Code (Internal View)


import
Comments // single line
/* */ multiline
/**
*/ Javadoc
Class definitions
public class Picture
{
// fields
// constructors
// methods
}

• writing a method
• methods vs fields vs local
variables
• Java statements
• accessor/mutator methods
Java
Dr. L. Lambert
CPSC150
Class Details: Methods

first line signature or header
(visible in external view also)
General Structure:
public/private return-type name (param1name
param1type, param2name param2type) return type void

changeColor method from Circle:
formal parameter
public void changeColor(String newColor)
curly braces, stuff
{
inside is method body
color = newColor;
draw( );
Java statements inside body,
e.g., single = assignment
}
Internal
method call
Java
Method call (with actual
parameters if necessary)
Dr. L. Lambert
CPSC150
Method vs. Field







Java
Both have private or public
Both have types
Both have names
fields have ‘;’ at end of line/methods do not
methods have ( ) (even without parameters); fields do
not
methods have a body; fields do not
fields have memory to hold information; methods do
not
Dr. L. Lambert
CPSC150
Field vs. Local variable





Java
local variables declare in a method; fields outside
of all methods
local variables have the lifetime of the method
call
local variables and fields have type and ‘;’
when possible, use local variables
local variables do NOT have private/public
designation
Dr. L. Lambert
CPSC150
Writing methods:
More Java statements







Java
Arithmetic Expressions
Compound Assignment
System.out.println
this
new
dot notation: external method calls
return
Dr. L. Lambert
CPSC150
Arithmetic

+, /, *, -, %

Be careful about integer division
4/3 p r 3
Use codepad (Choose view, then codepad)



Java
int answer=30; answer %= 4; System.out.println("Answer is " + answer);
Dr. L. Lambert
CPSC150
Compound Assignment

assignment:
answer = factor1 * factor2;
 answer = answer + newsum;


compound assignment
answer += newsum;
 answer -= diff;
 answer *= product; // e.g., factorial
 answer /= digit; // getting rid of digits
 answer %= digit;

Java
Dr. L. Lambert
CPSC150
Math Problems
Do on board
int x=3; double y=4.0;
x+y
x/2
y/3
x%2
x%3

Java
Dr. L. Lambert
CPSC150
System.out.println( )




To print out messages to a terminal
Can print strings or integers
Use + to concatenate/append. Be careful with
numbers
e.g.,
System.out.println("Answer is " + answer);
 System.out.println(answer + answer);
 System.out.println(“answer is” + answer + answer);

Java
Dr. L. Lambert
CPSC150
this
public void
changeColor(String newColor)
{
color = newColor;
draw( );
}
public void
changeColor(String color)
{
this.color = color;
draw( );
}
this specifies the
current object
Java
Dr. L. Lambert
CPSC150
new, dot notation
public void draw()
{
To create a new object,
use new. calls
constructor
wall = new Square( );
wall.moveVertical(80);
wall.changeSize(100);
wall.makeVisible();
External method call
dot notation
//rest of method from Picture class
}
Java
Dr. L. Lambert
CPSC150
Quiz Work

Print Picture.java from the BlueJ examples folder.
On that paper, write by hand (don’t type)
exercises 1.13 and 1.14, page 12.

Add by hand three methods:





Java
in Picture.java, write
addWindow that adds a
window to the other side of
the house (estimate where it
would be, or code it, then
write it down).
in Circle.java, write a constructor that takes two ints
and sets the Xposition field to the first and the
Yposition field to the second
in Circle.java, write an accessor method getSize
that returns the value of diameter
in Circle.java, write a mutator method setPosition
that takes two int parameters that represent the new
x and y position of the circle. If x >= 0 and <=
300 and y >= 0 and <= 300, change XPosition and
YPosition to be the values in the parameters and
redraw the Circle. Otherwise, do nothing. Start this
by coding it without the if.
Dr. L. Lambert
CPSC150
return statement
public int sum(int x, int y)
{
type of method is
return type
int answer;
answer = x+y;
to return a value, use ‘return
return answer;
value’; can be calculation
}
Java
Dr. L. Lambert
CPSC150
Common Methods to Write


Wizard at writing code; let’s look at common
methods
Mutator method: change value of a field


Accessor method: get the value of a field

Java
e.g., setTime in Clock
e.g., getTime in Clock
Dr. L. Lambert
CPSC150
Common methods: Accessor
Retrieve the value of a field
 no parameter, return type is type of field
 method body is one line
public class Fraction
{ // only a little bit defined
private int numerator;
private int denominator;

public int getNum()
{
return numerator;
}
}
Java
Dr. L. Lambert
CPSC150
Common Method: mutator
Changes field value
void return type, one parameter is new value
not all fields have to have mutator methods



public class fraction
{// only a portion of this class
private int numerator;
private int denominator;
public void setNum(int newvalue)
{
numerator = newvalue;
}
}
Java
Dr. L. Lambert
CPSC150
Work on Quiz 2

Print Picture.java from the BlueJ examples folder.
On that paper, write by hand (don’t type) exercises 1.13 and 1.14, page 12.

Add by hand three methods:





Java
in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it
would be, or code it, then write it down).
in Circle.java, write a constructor that takes two ints and sets the Xposition field to the first and the
Yposition field to the second
in Circle.java, write an accessor method getSize that
returns the value of diameter
in Circle.java, write a mutator method setPosition that
takes two int parameters that represent the new x and y
position of the circle. If x >= 0 and <= 300 and y >= 0
and <= 300, change XPosition and YPosition to be the
values in the parameters and redraw the Circle.
Otherwise, do nothing. Start this by coding it without
the if.
Dr. L. Lambert
CPSC150
Class Work
Write a Student class that has two fields, name (of type String) and
GPA (of type double). write accessor and mutator methods for
ONE of these fields. Write a print method that prints the fields
in the class.
Show your answer to 1-2 others, then write it on the board.
 printing is usually done with toString method which returns a
reasonable String representation of the class. Write toString
definition on the board.
 Change print to call toString
 Write a Class Course that has two students (student1 and
student2). Print out student1’s and student2’s info.
but don’t sit down yet
Java
Dr. L. Lambert
CPSC150
Quiz: Week 3






Java
Create a new project that has a Student class with two fields:
name (a String) and GPA (a double).
Write accessor, mutator and toString methods for the class.
Create two students on the object bench, and use the appropriate
methods to assign values . With inspect, show the values.
Capture the inspector window and print it.
Write another class in the same project, Course, that has two
Student fields. In the Course class constructor, create two
students and give values to the names and GPA. Have another
method toString that returns each student on a separate line (use
“\n” to put a new line in a string).
Create a Course object; call the toString method, and capture the
window that shows the console with the two students names.
Print the captured console window.
Print the Student and Course source code.
Dr. L. Lambert
CPSC150
Conditionals
Execute code under some conditions
 In Canvas
public static Canvas getCanvas()
{ // only create Canvas if not already created
if (canvasSingleton == null) {

canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, 300,
Color.white);
}
canvasSingleton.setVisible(true); // does this no matter what
return canvasSingleton;
}
Java
Dr. L. Lambert
CPSC150
if statements
if (booleanexpression)
java statement;
we don’t know about this
any Java statement you
know about
Java
Dr. L. Lambert
CPSC150
Boolean Expressions


Evaluate to be true or false
boolean variables



Java
boolean isVisible = false;
relational expressions (compares values)
logical expressions (compares expressions with
and, or, not)
Dr. L. Lambert
CPSC150
Relational Operators
for primitives
int x, y;
 x<y
 x <= y
 x>y
 x >= y
 x != y
 x == y // NOT x=y

Java
NOTE: most of these don’t work for classes (== is a
problem)
Dr. L. Lambert
CPSC150
Evaluating Boolean Expressions
Do on board with partners
int x=3; int y = 4; int z=5;
x<y
true
Java
x<y<z
error: < cannot be applied to boolean,int
x=y
error: incompatible types - found int; expected boolean
y == 4
true
z >= x
false
x != 3
false
(x + 4) < (y - 1)
7 < 3; false
Dr. L. Lambert
CPSC150
Logical Operators

and (&&, single & very different)



or (|| - on keyboard, called pipe symbol)



either value can be true
if it is cold or rainy, wear a coat (if either or both is true,
do)
not (!)


Java
both values must be true for the expression to be true
if it is cold and rainy, wear your winter raincoat (both
must be true)
changes the truth value of the expression
if it is not cold, do not wear a winter coat
Dr. L. Lambert
CPSC150
Logical Operators
Do on board
int x=3; int y=10;
(x < y) && (y < 20)
(x == 3) || (y == 3)
Java
x < y; 3 < 10; true
y < 20; 10 < 20; true
true && true is true
x == 3 true.
short circuit evaluation
(y==3 false
true || false is true)
Dr. L. Lambert
CPSC150
More logical operators
Do on board
int x=3; int y=10;
!(y=10)
(x != 3) || (y != 3)
Java
trick question
error
!(y==10)
y == 10 true
!true false
x != 3 false
Keep going. y != 3 true
false || true is true
Dr. L. Lambert
CPSC150
Yet more logical operators
Do on board
int x=3; int y=10;
!((x+1 < 4) ||
(y <= 10))
!((x+1 < 4) &&
(y <= 10))
Java
x+1 = 4
4 < 4 false.keep going
y <= 10 true
false || true true
! true is false
4 < 4 false. DONE with
&&. Do not look at y
<=10.
!false true
Dr. L. Lambert
CPSC150
Strings and Classes






Java
== tests if objects are equal (point to the same thing),
NOT if they have the same content. May return false
when true should be returned
use equals
no corresponding <, lessthan,…
use compareTo
Difference between primitives (holds a value) and
Classes (holds a pointer) is important.
= is for comparing if values are the same
Dr. L. Lambert
CPSC150
CompareTo



Java
Returns 0 if 2 Strings are equal
Returns negative number if object<parameter
Returns positive number if object > parameter
Dr. L. Lambert
CPSC150
compareTo code
write on board what will print
String s1 = “Here is a string”;
String s2 =“Here is another string”;
String s3 = “here is another string”;
if (s1.compareTo(s2) < 0)
// will print
System.out.println(“s1 less than s2”);
if (s2.compareTo(s1) < 0)
System.out.println(“s2 less than s1”); // will not print
if (s2.compareTo(s3) < 0) // case matters; uppercase < lowercase
System.out.println(“s2 less than s3”);
// will print
if (s3.compareTo(s2) < 0)
System.out.println(“s3 less than s2”); // will not print
Java
Dr. L. Lambert
CPSC150
More String comparisions
on board
String s1 = “Here is a string”;
String s2 =“Here is a string”;
String s3 = “here is another string”;
if (s1.compareTo(s2) == 0)
System.out.println(“s1 is the same as s2”); // will print
if (s2.compareTo(s1) == 0)
System.out.println(“s2 still the same as s1”); // will print; symmetric
if (s2.equals(s1)) // compareTo == 0 is same as equals
System.out.println(“s2 is STILL the same as s1”); // will print
if (s3.compareTo(s2) == 0)
System.out.println(“s3 is the same as s2”);
// will not print
if (s1 == s2)
// will not print
System.out.println(“s1 and s2 point to the same object”);
(done with board work)
Dr. L. Lambert
CPSC150
Java
if statements

if statement form:

if (boolean expression)
java statement;
if (x < y)
System.out.println(“x < y”);
Java
Dr. L. Lambert
you know both
parts now
CPSC150
if statements cautions







Java
MUST have ( )s around boolean expression
no syntax error for non-boolean like expressions
only ONE statement in an if statement
no ';' after if condition
Make sure you account for values that are equal
use relational operators only with primitives
use equals, compareTo with String
Dr. L. Lambert
CPSC150
if-else

If you want to do one thing if a condition is true
and something else if not, use if-else.
form: if (condition)
Java statement
else
Java statement
if (x < y)
System.out.println(x + " is less than the other number”);
else
System.out.println(y + " is less than the other number”);

Java
Dr. L. Lambert
CPSC150
> one statement in an if
If you want to have more than one statement inside an
if or an else, use {}s:
if (x < y)
{
System.out.println(x + " is less than the other number”);
x = 0;
}
else
{
System.out.println(y + " is less than the other number”);
y = 0;
}
Java
Dr. L. Lambert
CPSC150
If-else cautions




Java
either if clause or else clause or both may have
{}s.
After statements inside if and else clause are
executed, control passes back to next sequential
statement
no ';' after else
Make sure you account for values that are equal
Dr. L. Lambert
CPSC150
Class Work
Write an if statement to assign x to y if x is greater than
y
 Consider a class
public class MyString
{ private String s;
// write method here
}
Write the method lessThan that takes a String as a
parameter and returns true if s (from MyString) is less
than its String parameter

Java
Dr. L. Lambert
CPSC150
Watch Out
if (3 < 4)
x = 3;
else
System.out.println(“3 < 4 is false”);
x = 0;
System.out.println("the value of x is " + x);
Prints what?
Java
Dr. L. Lambert
CPSC150
Embedded ifs


Java
If statements and if-else statements may be
embedded (if within if). simply evaluate them as
the Java code is executed:
if-else example is most common. sets up a table
of conditions
Dr. L. Lambert
CPSC150
Embedded if-else for table
if (ave >= 90)
grade = 'A';
else if ((ave < 90) && (ave >= 80))
// note: need ()s around entire condition
grade = 'B';
else if ((ave < 80) && (ave >=70))
grade = 'C';
else if ((ave < 70) && (ave >=60))
grade = 'D';
else if ((ave < 70) && (ave < 60))
grade = 'F';
Java
Dr. L. Lambert
CPSC150
Tracing through the embedded if
Java
Dr. L. Lambert
CPSC150
Fixing the embedded if
Java
if (ave >= 90)
grade = 'A';
else if (ave >= 80)
// We know (ave < 90) or we wouldn't be here
grade = 'B';
else if (ave >=70) // we know ave < 80
grade = 'C';
else if (ave >=60)
grade = 'D';
else
// if ((ave < 70) && (ave < 60))
grade = 'F';
Dr. L. Lambert
CPSC150
Cautions for embedded ifs



Java
Don't use redundant comparisons
Make sure you check for values that are equal
Account for out of range values
Dr. L. Lambert
CPSC150
Program style




Java
Put {}s on a line by themselves
indent {}s 2-3 spaces, statements one more than
that
All code outside if statements should line up
All code inside of if statements should line up.
Dr. L. Lambert
CPSC150
More complicated embedded ifs
if (x < 3)
if (y < 6)
System.out.println( "x and y between 3 and 6");
else
System.out.println( "x < 3; y >= 6");
else
if (y > 6)
System.out.println( "x and y not in 3-6 range");
else
System.out.println( "x >= 3; y <= 6 ");
Write on board output for: (1) x is 3 and y is 6; (2) x is 0 and y is
0; (3) x is 0 and y is 6; (4) x is 99 and y is 6
Java
Dr. L. Lambert
CPSC150