cpsc150 spring 2006 dr. l lambert. week 1/2 intro (and chapter 1)

Post on 15-Jan-2016

220 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CPSC150

Spring 2006

Dr. L Lambert

Week 1/2

intro (and Chapter 1)

Syllabus

• 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.

Virtual Machine

• Review:– Computers understand machine language only– Each computer has its own language– No computer understands English, Powerpoint, or

Java

• Java developed to be platform independent– 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”

Why 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++)

Why BlueJ

• 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

Using Java and BlueJ

• 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)

Reading and Writing Java Code

Weeks 1 and 2

Chapters 1 and 2

By the end of this week, you should know how to:

• Write a Java program• Use BlueJ to write and run a Java program• Call methods from inside a program and from

the object bench• Use parameters in method definitions and

method calls• Use instance variables/fields• Create constructors• Write assignment statements • Write mathematical expressions

• object (on object bench and in source code)• class, instance• default constructor, overloading• method (definition)• method call• return value • parameter• source code • signature (in source code and external view)• formal parameter• actual parameter • type

Terms on test 1

Writing a Java program

// import statements if any

public class Name{// instance variables or fields// visible to all methods in class

// constructors. with no parameters is Default

// methods}

/** starts javadoc. TimesTable performs multiplication/times table */public class TimesTable // NO ( ) s in class{

private int factor; // field

/** have javadoc for every class, constructor and method * Constructor . without parameter, called default constructor. no return type

*/// return type void because nothing is returned public void TimesTable(int nbr) // actual parameter has type AND name { factor = nbr; // assignment statement } public int times(int nbr) // return type int { return nbr * factor; // math } // other methods go in here. printTimes(int nbr) and printTable( ) }

Do your own

On the board, with 1 or 2 others, write:

• printTimes(int nbr)

• printTable( )

// insert these methods into class on previous slidepublic void printTimes(int nbr) {// System.out.println changes System.out.println(factor + " times " + nbr + " is " + times(nbr)); } public void printTable( ) // methods start with lowercase { printTimes(0); printTimes(1); printTimes(2); printTimes(3); printTimes(4); printTimes(5); printTimes(6); printTimes(7); printTimes(8); printTimes(9); }

Class Details

• Using bluej

• Using methods

• Fields/instance variables

• constructors

• methods

Class details: fields/instance variables

• Lifetime/scope of class– field vs local variable

• private int myfield; // primitive– char, boolean, double, a few others

• private String mystring; // class• private Circle sun; // from Shapes

– user and library defined

• BlueJ: primitive has data; object has pointer

Source Code (Internal View)

• import• Comments // single line

/* */ multiline/** */ Javadoc

• Class definitionspublic class Picture{// fields// constructors// methods}

Class details: constructors• Initialize objects. Called when object is created• no return type• can be overloaded

public void TimesTable (int public void TimesTable (int nbr) nbr) {{ factor = nbr; factor = nbr; }}

public void TimesTable ( public void TimesTable ( ) ) {{ factor = 1; factor = 1; }}

Source Code (Internal View)

• import• Comments // single line

/* */ multiline/** */ Javadoc

• Class definitionspublic class Picture{// fields// constructors// methods}

• writing a method

• methods vs fields vs local variables

• Java statements

• accessor/mutator methods

Class Details: Methods

• General Structure:public/private return-type name (param1name

param1type, param2name param2type)

• times method from TimesTable: public int times(int nbr)

{

int answer;

answer = nbr * factor;

return answer;

}

return type int

first line signature or header (visible in external view also)

Java statements inside body, e.g., single = assignment

curly braces, stuff inside is method body

return statement

formal parameter list: type AND name

Local variabl

e

Method vs. Field

• 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

Field vs. Local variable

• 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

Writing methods:More Java statements

• Arithmetic Expressions

• Compound Assignment

• System.out.println

• this

• new

• dot notation: external method calls

• return

Arithmetic

• +, /, *, -, %

• Be careful about integer division• 4/3 r 3

• Use codepad (Choose view, then codepad)– int answer=30; answer %= 4; System.out.println("Answer is " +

answer);

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;

Math ProblemsDo on board

• int x=3; double y=4.0;

x + y

x / 2

y / 3

x % 2

x % 3

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

this

public void

changeColor(String newColor)

{

color = newColor;

draw( );

}

public void public void changeColor(String color)changeColor(String color) {{

this.color = color;this.color = color;draw( );draw( );

}}

this specifies the current object

new, dot notation

public void draw()

{

wall = new Square( );

wall.moveVertical(80);

wall.changeSize(100);

wall.makeVisible();//rest of method from Picture class

}

To create a new object, use new. calls

constructor

External method calldot notation

return statement

public int sum(int x, int y)

{

int answer;

answer = x+y;

return answer;

}

type of method is return type

to return a value, use ‘return value’; can be

calculation

Another Java Example: Picture.java

public class Picture{

private Square wall;private Square window;private Triangle roof;private Circle sun;

public Picture(){

// nothing to do... instance variables are automatically set to null}

// other methods}

Picture.javapublic void draw( )

{wall.makeVisible();window = new Square();window.changeColor("black");window.moveHorizontal(20);window.moveVertical(100);window.makeVisible();

roof = new Triangle();roof.changeSize(50, 140);roof.moveHorizontal(60);roof.moveVertical(70);roof.makeVisible();

sun = new Circle(); // set sun to be where it should be }

Picture.java

Constructor:– now: blank canvas like TV show– one option: create a finished picture– another option: create shapes, then put them

on

Modify to do second option

Picture.java

On the board, write a new constructor and a new draw( ) that creates the shapes, then puts them on

More Picture.javaon the board

• Write a new constructor in Circle.java that allows Circles to be created in the right place with the right color. For example, instead of

// oldsun = new Circle( );sun.changeColor("yellow");sun.moveHorizontal(180);sun.moveVertical(-10);sun.changeSize(60);sun.makeVisible( );

// new// xPosition = 180 + 20;// yPosition = 60-10sun = new Circle("yellow", 60, 200, 50);sun.makeVisible( );

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

Common methods: Accessor

• Retrieve the value of a part of a class, often a field• no parameter, return type is type of value being returned• method body is (often) one linepublic class Fraction{ // only a little bit defined private int numerator; private int denominator;

public int getNum() { return numerator; }}

Common Method: mutator• Changes field value• void return type, one parameter, the new value• not all fields have mutator methodspublic class fraction{// only a portion of this class private int numerator; private int denominator;

public void setNum(int newvalue) { numerator = newvalue; }}

Do on board

• Write a setFactor and a getFactor method

Conditionals

Conditionals

• Execute code under some conditions• In Canvaspublic 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;}

if statements

if (booleanexpression)

java statement;

any Java statement you know about

we don’t know about this

Boolean Expressions

• Evaluate to be true or false

• boolean variables– boolean isVisible = false;

• relational expressions (compares values)

• logical expressions (compares expressions with and, or, not)

Relational Operatorsfor primitives

int x, y;• x < y• x <= y• x > y• x >= y• x != y• x == y // NOT x=y

• NOTE: most of these don’t work for classes (== is a problem)

Evaluating Boolean ExpressionsDo on board with partners

int x=3; int y = 4; int z=5;int x=3; int y = 4; int z=5;

x < yx < y

x < y < zx < y < z

x = yx = y

y == 4y == 4

z >= xz >= x

x != 3x != 3

(x + 4) < (y - 1)(x + 4) < (y - 1)

truetrue

error: error: < cannot be applied to boolean,int< cannot be applied to boolean,int

error: incompatible types - found int; expected boolean error: incompatible types - found int; expected boolean

truetrue

falsefalse

falsefalse

7 < 3; false7 < 3; false

Logical Operators• and (&&, single & very different)

– 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)

• 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 (!)– changes the truth value of the expression– if it is not cold, do not wear a winter coat

Logical OperatorsDo on board

int x=3; int y=10;

(x < y) && (y < 20)

(x == 3) || (y == 3)

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)

More logical operatorsDo on board

int x=3; int y=10;

!(y=10)

(x != 3) || (y != 3)

trick question

error

!(y==10)

y == 10 true

!true false

x != 3 false

Keep going. y != 3 true

false || true is true

Yet more logical operatorsDo on board

int x=3; int y=10;

!((x+1 < 4) ||

(y <= 10))

!((x+1 < 4) &&

(y <= 10))

x+1 = 44 < 4 false.keep goingy <= 10 truefalse || true true! true is false4 < 4 false. DONE with

&&. Do not look at y <=10.

!false true

Strings and Classes

• == 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

CompareTo

• Returns 0 if 2 Strings are equal

• Returns negative number if object<parameter

• Returns positive number if object > parameter

compareTo codewrite 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) System.out.println(“s1 less than s2”); if (s2.compareTo(s1) < 0) System.out.println(“s2 less than s1”); if (s2.compareTo(s3) < 0) // case matters; uppercase <

lowercase System.out.println(“s2 less than s3”); if (s3.compareTo(s2) < 0) System.out.println(“s3 less than s2”);

// will print// will print

// will not print// will not print

// will print// will print

// will not print// will not print

More String comparisionson 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”);if (s2.compareTo(s1) == 0) System.out.println(“s2 still the same as s1”);if (s2.equals(s1)) System.out.println(“s2 is STILL the same as s1”);if (s3.compareTo(s2) == 0) System.out.println(“s3 is the same as s2”);if (s1 == s2) System.out.println(“s1 and s2 point to the same object”);(done with board work)

// will not print// will not print

// will print; symmetric// will print; symmetric

// will print// will print

// will print// will print

// will not print// will not print

// compareTo == 0 is same as equals// compareTo == 0 is same as equals

if statements• if statement form:

– if (boolean expression)

java statement;

if (x < y)

System.out.println(“x < y”);

you know both parts

now

if statements cautions• 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

Do on board

• Write an if statement that prints "Before Middle" if String x is alphabetically less than middle and "After Middle" otherwise

What’s logically wrong with this?

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

> one statement in an ifIf 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;

}

If-else cautions

• 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

Class Work

• Write an if statement to assign x to y if x is greater than y

• Consider a classpublic 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

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?

Embedded ifs

• 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

Embedded if-else for tableif (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';

Tracing through the embedded if

Fixing the embedded ifif (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';

Cautions for embedded ifs

• Don't use redundant comparisons

• Make sure you check for values that are equal

• Account for out of range values

Program style

• 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.

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

top related