cpsc150 javadr. l. lambert cpsc150 fall 2005 dr. l lambert
Post on 19-Dec-2015
221 Views
Preview:
TRANSCRIPT
Java Dr. L. Lambert CPSC150
CPSC150CPSC150
Fall 2005Fall 2005
Dr. L LambertDr. L Lambert
Java Dr. L. Lambert CPSC150
Week 1Week 1
Chapter 1Chapter 1
Java, BlueJ, Objects, TermsJava, BlueJ, Objects, Terms
Java Dr. L. Lambert CPSC150
SyllabusSyllabus
JavaJava CPSC150LabCPSC150Lab Attendance, but does not countAttendance, but does not count weekly quiz. Due the next week. Graded. weekly quiz. Due the next week. Graded.
Collaborative. Come prepared to work on it Collaborative. Come prepared to work on it in class.in class.
Come see me/Java expert early and oftenCome see me/Java expert early and often Ask questionsAsk questions Consult with (possibly non-expert) peers, but Consult with (possibly non-expert) peers, but
be careful. >50% of your grade is exams.be careful. >50% of your grade is exams.
Java Dr. L. Lambert CPSC150
Quiz: week 1Quiz: week 1 Using the Shapes example, draw a Using the Shapes example, draw a
snowman in BlueJ (by creating objects snowman in BlueJ (by creating objects and modifying them) that looks like and modifying them) that looks like this (exact dimensions and placement this (exact dimensions and placement are not important).are not important).
Capture the image and window with Capture the image and window with the object bench (yours will not be the object bench (yours will not be empty as this one is)empty as this one is)
Print source code for one Class (e.g., Print source code for one Class (e.g., Circle)Circle)
Identify in these three at least one of Identify in these three at least one of each of the following: object, Class, each of the following: object, Class, method call, parameter, instance, method call, parameter, instance, method (definition), signature, type, method (definition), signature, type, source code, return valuesource code, return value
Turn in a printed copy of: captured Turn in a printed copy of: captured image, captured BlueJ window, source image, captured BlueJ window, source code for one Class. Terms should be code for one Class. Terms should be identified on each as appropriate.identified on each as appropriate.
Java Dr. L. Lambert CPSC150
Virtual MachineVirtual Machine Review:Review:
Computers understand machine language onlyComputers understand machine language only Each computer has its own languageEach computer has its own language No computer understands English, Powerpoint, No computer understands English, Powerpoint,
or Javaor Java
Java developed to be platform independentJava developed to be platform independent Virtual machine built on top of each actual Virtual machine built on top of each actual
machine to make all machines (windows, mac, machine to make all machines (windows, mac, UNIX) look alikeUNIX) look alike
Java compiles to byte-code – not machine code, Java compiles to byte-code – not machine code, but “virtual machine code”but “virtual machine code”
Java Dr. L. Lambert CPSC150
Why Java?Why Java?
Java is a large, complete languageJava is a large, complete language Works well with web applicationsWorks well with web applications GUIs “part” of the languageGUIs “part” of the language Extensive librariesExtensive libraries (Other CS courses will cover C++)(Other CS courses will cover C++)
Java Dr. L. Lambert CPSC150
Why BlueJWhy BlueJ
Easy to useEasy to use Object-orientedObject-oriented Start programming immediatelyStart programming immediately GUI, not console-basedGUI, not console-based Object visualization using UMLObject visualization using UML Debugger, Editor, other standard stuffDebugger, Editor, other standard stuff Simple, not for advanced applicationsSimple, not for advanced applications
Java Dr. L. Lambert CPSC150
Using Java and BlueJUsing Java and BlueJ We will use BlueJ for program developmentWe will use BlueJ for program development BlueJ runs on the Java virtual machineBlueJ runs on the Java virtual machine BlueJ is IDE – lots of others (e.g., Eclipse)BlueJ is IDE – lots of others (e.g., Eclipse) BlueJ is free and available for Mac, Windows, BlueJ is free and available for Mac, Windows,
UNIXUNIX You will test and submit program using UNIXYou will test and submit program using UNIX Use your Hunter Creech AccountUse your Hunter Creech Account Download BlueJ for your home machines for Download BlueJ for your home machines for
development: development: www.bluej.orgwww.bluej.org (download Java 1.5 first): (download Java 1.5 first):
http://java.sun.com/j2se/1.5.0/download.jsp http://java.sun.com/j2se/1.5.0/download.jsp (Download (Download SDKSDK, NOT , NOT JREJRE))
Java Dr. L. Lambert CPSC150
• 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 .
Looking at an Example:Looking at an Example:External ViewExternal View
(dot MUST be there)
Java Dr. L. Lambert CPSC150
Reading and Reading and Writing Java Writing Java
CodeCodeWeeks 1 and 2Weeks 1 and 2
Chapters 1 and 2Chapters 1 and 2
Java Dr. L. Lambert CPSC150
Quiz: week 2Quiz: week 2(= you know enough to do (= you know enough to do
Quiz 1)Quiz 1) Print Picture.java from the BlueJ examples folder.Print Picture.java from the BlueJ examples folder. On that paper, write On that paper, write by hand by hand (don’t type) exercises 1.13 (don’t type) exercises 1.13
and 1.14, page 12.and 1.14, page 12. Add Add by handby hand three methods: three methods:
in Picture.java, write in Picture.java, write addWindowaddWindow that adds a window to the other that adds a window to the other side of the house (estimate where it would be, or code it, then side of the house (estimate where it would be, or code it, then write it down).write it down).
in Circle.java, write a constructor that takes two ints and sets the 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 Xposition field to the first and the Yposition field to the second
in Circle.java, write an accessor method in Circle.java, write an accessor method getSizegetSize that returns the that returns the value of diametervalue of diameter
in Circle.java, write a mutator method setPosition that takes two in Circle.java, write a mutator method setPosition that takes two int parameters that represent the new x and y position of the int parameters that represent the new x and y position of the circle. If x >= 0 and <= 300 and y >= 0 and <= 300, change circle. If x >= 0 and <= 300 and y >= 0 and <= 300, change XPosition and YPosition to be the values in the parameters and XPosition and YPosition to be the values in the parameters and redraw the Circle. Otherwise, do nothing. redraw the Circle. Otherwise, do nothing. Start this by coding Start this by coding it without the if.it without the if.
Java Dr. L. Lambert CPSC150
ReviewReview
External ViewExternal View In BlueJ main window, In BlueJ main window,
ClassesClasses Object benchObject bench Class relationships Class relationships Create ObjectsCreate Objects Call/Invoke Methods of objectsCall/Invoke Methods of objects
Java Dr. L. Lambert CPSC150
Source Code (Internal Source Code (Internal View)View)
importimport Comments Comments // single line// single line
/* */ multiline/* */ multiline/** */ Javadoc/** */ Javadoc
Class definitionsClass definitionspublic class Picturepublic class Picture{{// fields// fields// constructors// constructors// methods// methods}}
Java Dr. L. Lambert CPSC150
Class details: Class details: fields/instance variablesfields/instance variables
Lifetime/scope of classLifetime/scope of class field vs local variablefield vs local variable
private int myfield; // primitiveprivate int myfield; // primitive char, boolean, double, a few otherschar, boolean, double, a few others
private String mystring; // classprivate String mystring; // class private Circle sun;private Circle sun;
user and library defineduser and library defined BlueJ: primitive has data; object has pointerBlueJ: primitive has data; object has pointer
Clock example, ClockDisplay, NumberDisplayClock example, ClockDisplay, NumberDisplay(Inspect object in (Inspect object in
/home/lambert/Public/projects/chapter03/clock-/home/lambert/Public/projects/chapter03/clock-display)display)
Java Dr. L. Lambert CPSC150
Source Code (Internal Source Code (Internal View)View)
importimport Comments Comments // single line// single line
/* */ multiline/* */ multiline/** */ Javadoc/** */ Javadoc
Class definitionsClass definitionspublic class Picturepublic class Picture{{// fields// fields// constructors// constructors// methods// methods}}
Java Dr. L. Lambert CPSC150
Class details: Class details: constructorsconstructors
Initialize objects. Called when object is createdInitialize objects. Called when object is created no return typeno return type can be overloadedcan be overloaded
public Circle( )public Circle( ) { // give fields default values{ // give fields default values
diameter = 30;diameter = 30;xPosition = 20;xPosition = 20;yPosition = 60;yPosition = 60;color = "blue";color = "blue";isVisible = false;isVisible = false;
}}
public Circle(int d, int x, int y, color public Circle(int d, int x, int y, color c)c) { // give fields client-specified { // give fields client-specified valuesvalues
diameter = d;diameter = d;xPosition = x;xPosition = x;yPosition = y;yPosition = y;color = c;color = c;isVisible = false;isVisible = false;
}}
Java Dr. L. Lambert CPSC150
Work on Quiz TimeWork on Quiz Time Print Picture.java from the BlueJ examples folder.Print Picture.java from the BlueJ examples folder. On that paper, write On that paper, write by hand by hand (don’t type) exercises 1.13 and 1.14, (don’t type) exercises 1.13 and 1.14,
page 12.page 12. Add Add by handby hand three methods: three methods:
in Picture.java, write addWindow that adds a window in Picture.java, write addWindow that adds a window to the other side of the house (estimate where it would to the other side of the house (estimate where it would be, or code it, then write it down).be, or code it, then write it down).
in Circle.java, write a constructor that in Circle.java, write a constructor that takes two ints and sets the Xposition takes two ints and sets the Xposition field to the first and the Yposition field field to the first and the Yposition field to the second 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.
Java Dr. L. Lambert CPSC150
Source Code (Internal Source Code (Internal View)View)
importimport Comments Comments // single line// single line
/* */ multiline/* */ multiline/** */ Javadoc/** */ Javadoc
Class definitionsClass definitionspublic class Picturepublic class Picture{{// fields// fields// constructors// constructors// methods// methods}}
• writing a method
• methods vs fields vs local variables
• Java statements
• accessor/mutator methods
Java Dr. L. Lambert CPSC150
Class Details: MethodsClass Details: Methods
General Structure:General Structure:public/private return-type name public/private return-type name
(param1name param1type, param2name (param1name param1type, param2name param2type)param2type)
changeColor method from Circle:changeColor method from Circle: public void changeColor(String newColor)public void changeColor(String newColor) {{
color = newColor;color = newColor;draw( );draw( );
}}
return type void
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
formal parameter
Internal method call
Method call (with actual parameters if necessary)
Java Dr. L. Lambert CPSC150
Method vs. FieldMethod vs. Field
Both have private or publicBoth have private or public Both have typesBoth have types Both have namesBoth have names fields have ‘;’ at end of line/methods do notfields have ‘;’ at end of line/methods do not methods have ( ) (even without methods have ( ) (even without
parameters); fields do notparameters); fields do not methods have a body; fields do notmethods have a body; fields do not fields have memory to hold information; fields have memory to hold information;
methods do notmethods do not
Java Dr. L. Lambert CPSC150
Field vs. Local variableField vs. Local variable
local variables declare in a method; local variables declare in a method; fields outside of all methodsfields outside of all methods
local variables have the lifetime of the local variables have the lifetime of the method callmethod call
local variables and fields have type local variables and fields have type and ‘;’and ‘;’
when possible, use local variableswhen possible, use local variables local variables do NOT have local variables do NOT have
private/public designationprivate/public designation
Java Dr. L. Lambert CPSC150
Writing methods:Writing methods:More Java statementsMore Java statements
Arithmetic ExpressionsArithmetic Expressions Compound AssignmentCompound Assignment System.out.printlnSystem.out.println thisthis newnew dot notation: external method callsdot notation: external method calls returnreturn
Java Dr. L. Lambert CPSC150
ArithmeticArithmetic +, /, *, -, %+, /, *, -, %
Be careful about integer divisionBe careful about integer division 4/3 4/3 rr 3 3
Use codepad (Choose view, then codepad)Use codepad (Choose view, then codepad) int answer=30; answer %= 4; int answer=30; answer %= 4;
System.out.println("Answer is " + answer);System.out.println("Answer is " + answer);
Java Dr. L. Lambert CPSC150
Compound AssignmentCompound Assignment
assignment:assignment: answer = factor1 * factor2;answer = factor1 * factor2; answer = answer + newsum;answer = answer + newsum;
compound assignmentcompound assignment answer += newsum;answer += newsum; answer -= diff;answer -= diff; answer *= product; // e.g., factorialanswer *= product; // e.g., factorial answer /= digit; // getting rid of digitsanswer /= digit; // getting rid of digits answer %= digit; answer %= digit;
Java Dr. L. Lambert CPSC150
Math ProblemsMath ProblemsDo on boardDo on board
int x=3; double y=4.0;int x=3; double y=4.0;
x+yx+y
x/2x/2
y/3y/3
x%2x%2
x%3x%3
Java Dr. L. Lambert CPSC150
System.out.println( )System.out.println( )
To print out messages to a terminalTo print out messages to a terminal Can print strings or integersCan print strings or integers Use + to concatenate/append. Be Use + to concatenate/append. Be
careful with numberscareful with numbers e.g.,e.g.,
System.out.println("Answer is " + answer); System.out.println("Answer is " + answer); System.out.println(answer + answer);System.out.println(answer + answer); System.out.println(“answer is” + answer + System.out.println(“answer is” + answer +
answer);answer);
Java Dr. L. Lambert CPSC150
thisthis
public void public void
changeColor(String newColor)changeColor(String newColor)
{{
color = newColor;color = newColor;
draw( );draw( );
}}
public void public void changeColor(String color)changeColor(String color) {{
this.color = color;this.color = color;draw( );draw( );
}}
this specifies the current object
Java Dr. L. Lambert CPSC150
new, dot notationnew, dot notation
public void draw()public void draw()
{{
wall = new Square( );wall = new Square( );
wall.moveVertical(80);wall.moveVertical(80);
wall.changeSize(100);wall.changeSize(100);
wall.makeVisible();wall.makeVisible();//rest of method from Picture class//rest of method from Picture class
}}
To create a new object, use new. calls
constructor
External method calldot notation
Java Dr. L. Lambert CPSC150
Quiz WorkQuiz Work Print Picture.java from the BlueJ Print Picture.java from the BlueJ
examples folder.examples folder. On that paper, write On that paper, write by hand by hand (don’t type) (don’t type)
exercises 1.13 and 1.14, page 12.exercises 1.13 and 1.14, page 12. Add Add by handby hand three methods: three methods:
in Picture.java, write in Picture.java, write addWindow that adds a addWindow that adds a window to the other window to the other side of the house side of the house (estimate where it (estimate where it would be, or code it, would be, or code it, then write it down).then write it down).
in Circle.java, write a constructor that takes in Circle.java, write a constructor that takes two ints and sets the Xposition field to the two ints and sets the Xposition field to the first and the Yposition field to the second 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.
Java Dr. L. Lambert CPSC150
return statementreturn statement
public int sum(int x, int y)public int sum(int x, int y)
{{
int answer;int answer;
answer = x+y;answer = x+y;
return answer;return answer;
}}
type of method is return type
to return a value, use ‘return value’; can be
calculation
Java Dr. L. Lambert CPSC150
Common Methods to Common Methods to WriteWrite
Wizard at writing code; let’s look at Wizard at writing code; let’s look at common methodscommon methods
Mutator method: change value of a Mutator method: change value of a fieldfield e.g., setTime in Clocke.g., setTime in Clock
Accessor method: get the value of a Accessor method: get the value of a fieldfield e.g., getTime in Clocke.g., getTime in Clock
Java Dr. L. Lambert CPSC150
Common methods: Common methods: AccessorAccessor
Retrieve the value of a fieldRetrieve the value of a field no parameter, return type is type of fieldno parameter, return type is type of field method body is one linemethod body is one linepublic class Fractionpublic class Fraction{ // only a little bit defined{ // only a little bit defined private int numerator;private int numerator; private int denominator;private int denominator;
public int getNum()public int getNum() {{ return numerator;return numerator; }}}}
Java Dr. L. Lambert CPSC150
Common Method: Common Method: mutatormutator
Changes field valueChanges field value void return type, one parameter is new valuevoid return type, one parameter is new value not all fields have to have mutator methodsnot all fields have to have mutator methodspublic class fractionpublic class fraction{// only a portion of this class{// only a portion of this class private int numerator;private int numerator; private int denominator;private int denominator;
public void setNum(int newvalue)public void setNum(int newvalue) {{ numerator = newvalue;numerator = newvalue; }}}}
Java Dr. L. Lambert CPSC150
Work on Quiz 2Work on Quiz 2 Print Picture.java from the BlueJ examples folder.Print Picture.java from the BlueJ examples folder. On that paper, write On that paper, write by hand by hand (don’t type) exercises 1.13 and 1.14, page 12.(don’t type) exercises 1.13 and 1.14, page 12. Add Add by handby hand three methods: three methods:
in Picture.java, write addWindow that adds a window to the other side of the 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).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 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 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.
Java Dr. L. Lambert CPSC150
Class WorkClass WorkWrite a Student class that has two fields, name (of type String) and Write a Student class that has two fields, name (of type String) and
GPA (of type double). write accessor and mutator methods for GPA (of type double). write accessor and mutator methods for ONE of these fields. Write a print method that prints the fields in ONE of these fields. Write a print method that prints the fields in the class.the class.
Show your answer to 1-2 others, then write it on the board.Show your answer to 1-2 others, then write it on the board. printing is usually done with toString method which returns a printing is usually done with toString method which returns a
reasonable String representation of the class. Write toString reasonable String representation of the class. Write toString definition on the board. definition on the board.
Change print to call toStringChange print to call toString Write a Class Course that has two students (student1 and Write a Class Course that has two students (student1 and
student2). Print out student1’s and student2’s info.student2). Print out student1’s and student2’s info.
but don’t sit down yetbut don’t sit down yet
Java Dr. L. Lambert CPSC150
Quiz: Week 3Quiz: Week 3 Create a new project that has a Create a new project that has a StudentStudent class with two class with two
fields: name (a String) and GPA (a double).fields: name (a String) and GPA (a double). Write accessor, mutator and toString methods for the Write accessor, mutator and toString methods for the
class.class. Create two students on the object bench, and use the Create two students on the object bench, and use the
appropriate methods to assign values . With inspect, show appropriate methods to assign values . With inspect, show the values. Capture the inspector window and print it.the values. Capture the inspector window and print it.
Write another class in the same project,Write another class in the same project, Course Course, that has , that has two Student fields. In the Course class constructor, create two Student fields. In the Course class constructor, create two students and give values to the names and GPA. Have two students and give values to the names and GPA. Have another method toString that returns each student on a another method toString that returns each student on a separate line (use “\n” to put a new line in a string). separate line (use “\n” to put a new line in a string).
Create a Course object; call the toString method, and Create a Course object; call the toString method, and capture the window that shows the console with the two capture the window that shows the console with the two students names. Print the captured console window.students names. Print the captured console window.
Print the Student and Course source code.Print the Student and Course source code.
Java Dr. L. Lambert CPSC150
ConditionalsConditionals Execute code under some conditionsExecute code under some conditions In CanvasIn Canvaspublic static Canvas getCanvas()public static Canvas getCanvas()
{ // only create Canvas if not already created{ // only create Canvas if not already created if (canvasSingleton == null) {if (canvasSingleton == null) {
canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, canvasSingleton = new Canvas("BlueJ Shapes Demo", 300, 300, 300,
Color.white);Color.white);
}} canvasSingleton.setVisible(true); // does this no canvasSingleton.setVisible(true); // does this no matter whatmatter what return canvasSingleton;return canvasSingleton;}}
Java Dr. L. Lambert CPSC150
if statementsif statements
if (booleanexpression)if (booleanexpression)
java statement;java statement;
any Java statement you know about
we don’t know about this
Java Dr. L. Lambert CPSC150
Boolean ExpressionsBoolean Expressions
Evaluate to be true or falseEvaluate to be true or false boolean variablesboolean variables
boolean isVisible = false;boolean isVisible = false; relational expressions (compares relational expressions (compares
values)values) logical expressions (compares logical expressions (compares
expressions with and, or, not)expressions with and, or, not)
Java Dr. L. Lambert CPSC150
Relational OperatorsRelational Operatorsfor primitivesfor primitives
int x, y;int x, y; x < yx < y x <= yx <= y x > yx > y x >= yx >= y x != yx != y x == y // NOT x=yx == y // NOT x=y
NOTE: most of these don’t work for NOTE: most of these don’t work for classes (== is a problem)classes (== is a problem)
Java Dr. L. Lambert CPSC150
Evaluating Boolean Evaluating Boolean ExpressionsExpressions
Do on board with partnersDo on board with partnersint 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
Java Dr. L. Lambert CPSC150
Logical OperatorsLogical Operators and (&&, single & very different)and (&&, single & very different)
both values must be true for the expression to be both values must be true for the expression to be truetrue
if it is cold and rainy, wear your winter raincoat if it is cold and rainy, wear your winter raincoat (both must be true)(both must be true)
or (|| - on keyboard, called pipe symbol)or (|| - on keyboard, called pipe symbol) either value can be trueeither value can be true if it is cold or rainy, wear a coat (if either or both is if it is cold or rainy, wear a coat (if either or both is
true, do)true, do) not (!)not (!)
changes the truth value of the expressionchanges the truth value of the expression if it is not cold, do not wear a winter coatif it is not cold, do not wear a winter coat
Java Dr. L. Lambert CPSC150
Logical OperatorsLogical OperatorsDo on boardDo on board
int x=3; int y=10;int x=3; int y=10;
(x < y) && (y < 20)(x < y) && (y < 20)
(x == 3) || (y == 3)(x == 3) || (y == 3)
x < y; 3 < 10; truex < y; 3 < 10; true
y < 20; 10 < 20; truey < 20; 10 < 20; true
true && true is truetrue && true is true
x == 3 true.x == 3 true.
short circuit short circuit evaluationevaluation
(y==3 false(y==3 false
true || false is true)true || false is true)
Java Dr. L. Lambert CPSC150
More logical operatorsMore logical operatorsDo on boardDo on board
int x=3; int y=10;int x=3; int y=10;
!(y=10)!(y=10)
(x != 3) || (y != 3)(x != 3) || (y != 3)
trick questiontrick question
errorerror
!(y==10)!(y==10)
y == 10 truey == 10 true
!true false!true false
x != 3 falsex != 3 false
Keep going. y != 3 Keep going. y != 3 truetrue
false || true is truefalse || true is true
Java Dr. L. Lambert CPSC150
Yet more logical operatorsYet more logical operatorsDo on boardDo on board
int x=3; int y=10;int x=3; int y=10;!((x+1 < 4) ||!((x+1 < 4) ||
(y <= 10))(y <= 10))
!((x+1 < 4) &&!((x+1 < 4) &&
(y <= 10))(y <= 10))
x+1 = 4x+1 = 44 < 4 false.keep 4 < 4 false.keep
goinggoingy <= 10 truey <= 10 truefalse || true truefalse || true true! true is false! true is false4 < 4 false. DONE 4 < 4 false. DONE
with &&. Do not with &&. Do not look at y <=10.look at y <=10.
!false true!false true
Java Dr. L. Lambert CPSC150
Strings and ClassesStrings and Classes == tests if objects are equal (point to the == tests if objects are equal (point to the
same thing), NOT if they have the same same thing), NOT if they have the same content. May return false when true should content. May return false when true should be returnedbe returned
use equalsuse equals no corresponding <, lessthan,…no corresponding <, lessthan,… use compareTouse compareTo
Difference between primitives (holds a value) Difference between primitives (holds a value) and Classes (holds a pointer) is important.and Classes (holds a pointer) is important.
= is for comparing if values are the same= is for comparing if values are the same
Java Dr. L. Lambert CPSC150
CompareToCompareTo
Returns 0 if 2 Strings are equalReturns 0 if 2 Strings are equal Returns negative number if Returns negative number if
object<parameterobject<parameter Returns positive number if object > Returns positive number if object >
parameterparameter
Java Dr. L. Lambert CPSC150
compareTo codecompareTo codewrite on board what will write on board what will
printprintString s1 = “Here is a string”;String s1 = “Here is a string”;String s2 =“Here is another string”;String s2 =“Here is another string”;String s3 = “here is another string”;String s3 = “here is another string”;if (s1.compareTo(s2) < 0)if (s1.compareTo(s2) < 0) System.out.println(“s1 less than s2”); System.out.println(“s1 less than s2”); if (s2.compareTo(s1) < 0)if (s2.compareTo(s1) < 0) System.out.println(“s2 less than s1”); System.out.println(“s2 less than s1”); if (s2.compareTo(s3) < 0) // case matters; uppercase if (s2.compareTo(s3) < 0) // case matters; uppercase
< lowercase< lowercase System.out.println(“s2 less than s3”); System.out.println(“s2 less than s3”); if (s3.compareTo(s2) < 0)if (s3.compareTo(s2) < 0) System.out.println(“s3 less than s2”); 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
Java Dr. L. Lambert CPSC150
More String comparisionsMore String comparisionson boardon board
String s1 = “Here is a string”;String s1 = “Here is a string”;String s2 =“Here is a string”;String s2 =“Here is a string”;String s3 = “here is another string”;String s3 = “here is another string”;if (s1.compareTo(s2) == 0)if (s1.compareTo(s2) == 0) System.out.println(“s1 is the same as s2”);System.out.println(“s1 is the same as s2”);if (s2.compareTo(s1) == 0)if (s2.compareTo(s1) == 0) System.out.println(“s2 still the same as s1”);System.out.println(“s2 still the same as s1”);if (s2.equals(s1))if (s2.equals(s1)) System.out.println(“s2 is STILL the same as s1”);System.out.println(“s2 is STILL the same as s1”);if (s3.compareTo(s2) == 0) if (s3.compareTo(s2) == 0) System.out.println(“s3 is the same as s2”);System.out.println(“s3 is the same as s2”);if (s1 == s2)if (s1 == s2) System.out.println(“s1 and s2 point to the same object”);System.out.println(“s1 and s2 point to the same object”);(done with board work)(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
Java Dr. L. Lambert CPSC150
if statementsif statements if statement form:if statement form:
if (boolean expression) if (boolean expression)
java statement;java statement;
if (x < y)if (x < y)
System.out.println(“x < y”);System.out.println(“x < y”);
you know both parts
now
Java Dr. L. Lambert CPSC150
if statements cautionsif statements cautions MUST have ( )s around boolean expressionMUST have ( )s around boolean expression no syntax error for non-boolean like no syntax error for non-boolean like
expressionsexpressions only ONE statement in an if statementonly ONE statement in an if statement no ';' after if conditionno ';' after if condition Make sure you account for values that are Make sure you account for values that are
equalequal use relational operators only with use relational operators only with
primitivesprimitives use equals, compareTo with Stringuse equals, compareTo with String
Java Dr. L. Lambert CPSC150
if-elseif-else
If you want to do one thing if a condition is If you want to do one thing if a condition is true and something else if not, use if-else.true and something else if not, use if-else. form: if (condition)form: if (condition)
Java statementJava statement elseelse Java statementJava statement
if (x < y)if (x < y) System.out.println(x + " is less than the other System.out.println(x + " is less than the other
number”);number”);elseelse System.out.println(y + " is less than the other System.out.println(y + " is less than the other
number”);number”);
Java Dr. L. Lambert CPSC150
> one statement in an if> one statement in an ifIf you want to have more than one statement If you want to have more than one statement
inside an if or an else, use {}s:inside an if or an else, use {}s:if (x < y) if (x < y)
{{
System.out.println(x + " is less than the System.out.println(x + " is less than the other number”);other number”);
x = 0;x = 0;
}}
elseelse
{{
System.out.println(y + " is less than the other System.out.println(y + " is less than the other number”);number”);
y = 0;y = 0;
}}
Java Dr. L. Lambert CPSC150
If-else cautionsIf-else cautions
either if clause or else clause or both either if clause or else clause or both may have {}s.may have {}s.
After statements inside if and else After statements inside if and else clause are executed, control passes clause are executed, control passes back to next sequential statementback to next sequential statement
no ';' after elseno ';' after else Make sure you account for values Make sure you account for values
that are equalthat are equal
Java Dr. L. Lambert CPSC150
Class WorkClass Work Write an if statement to assign x to y if x is Write an if statement to assign x to y if x is
greater than ygreater than y Consider a classConsider a classpublic class MyStringpublic class MyString{ private String s;{ private String s;// write method here// write method here}}Write the method lessThan that takes a String Write the method lessThan that takes a String
as a parameter and returns true if s (from as a parameter and returns true if s (from MyString) is less than its String parameterMyString) is less than its String parameter
Java Dr. L. Lambert CPSC150
Watch OutWatch Out
if (3 < 4)if (3 < 4)
x = 3;x = 3;
elseelse
System.out.println(“3 < 4 is false”);System.out.println(“3 < 4 is false”);
x = 0;x = 0;
System.out.println(System.out.println("the value of x is " + x);"the value of x is " + x);
Prints what?Prints what?
Java Dr. L. Lambert CPSC150
Embedded ifsEmbedded ifs
If statements and if-else statements If statements and if-else statements may be embedded (if within if). may be embedded (if within if). simply evaluate them as the Java simply evaluate them as the Java code is executed:code is executed:
if-else example is most common. if-else example is most common. sets up a table of conditionssets up a table of conditions
Java Dr. L. Lambert CPSC150
Embedded if-else for Embedded if-else for tabletable
if (ave >= 90)if (ave >= 90) grade = 'A';grade = 'A';else if ((ave < 90) && (ave >= 80))else if ((ave < 90) && (ave >= 80)) // note: need ()s around entire condition// note: need ()s around entire condition grade = 'B'; grade = 'B'; else if ((ave < 80) && (ave >=70))else if ((ave < 80) && (ave >=70)) grade = 'C';grade = 'C';else if ((ave < 70) && (ave >=60))else if ((ave < 70) && (ave >=60)) grade = 'D';grade = 'D';else if ((ave < 70) && (ave < 60))else if ((ave < 70) && (ave < 60)) grade = 'F';grade = 'F';
Java Dr. L. Lambert CPSC150
Tracing through the Tracing through the embedded ifembedded if
Java Dr. L. Lambert CPSC150
Fixing the embedded ifFixing the embedded ifif (ave >= 90)if (ave >= 90) grade = 'A';grade = 'A';else if (ave >= 80)else if (ave >= 80)// We know (ave < 90) or we wouldn't be // We know (ave < 90) or we wouldn't be
herehere grade = 'B'; grade = 'B'; else if (ave >=70) // we know ave < 80else if (ave >=70) // we know ave < 80 grade = 'C';grade = 'C';else if (ave >=60)else if (ave >=60) grade = 'D';grade = 'D';else else // if ((ave < 70) && (ave < 60))// if ((ave < 70) && (ave < 60)) grade = 'F';grade = 'F';
Java Dr. L. Lambert CPSC150
Cautions for embedded Cautions for embedded ifsifs
Don't use redundant comparisonsDon't use redundant comparisons Make sure you check for values that Make sure you check for values that
are equalare equal Account for out of range valuesAccount for out of range values
Java Dr. L. Lambert CPSC150
Program styleProgram style
Put {}s on a line by themselvesPut {}s on a line by themselves indent {}s 2-3 spaces, statements indent {}s 2-3 spaces, statements
one more than thatone more than that All code outside if statements should All code outside if statements should
line upline up All code inside of if statements All code inside of if statements
should line up.should line up.
Java Dr. L. Lambert CPSC150
More complicated More complicated embedded ifsembedded ifs
if (x < 3)if (x < 3) if (y < 6)if (y < 6) System.out.println( "x and y between 3 and 6");System.out.println( "x and y between 3 and 6"); elseelse System.out.println( "x < 3; y >= 6");System.out.println( "x < 3; y >= 6");elseelse if (y > 6)if (y > 6) System.out.println( "x and y not in 3-6 range"); System.out.println( "x and y not in 3-6 range"); elseelse System.out.println( "x >= 3; y <= 6 ");System.out.println( "x >= 3; y <= 6 ");
Write on board output for: (1) x is 3 and y is 6; (2) 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 x is 0 and y is 0; (3) x is 0 and y is 6; (4) x is 99 and y is 6and y is 6
top related