21
Introduction to Introduction to Programming Programming Writing Java Beginning Writing Java Beginning Java Programs Java Programs

Introduction to Programming Writing Java Beginning Java Programs

Embed Size (px)

Citation preview

Page 1: Introduction to Programming Writing Java Beginning Java Programs

Introduction to Introduction to ProgrammingProgramming

Writing Java Beginning Java Writing Java Beginning Java ProgramsPrograms

Page 2: Introduction to Programming Writing Java Beginning Java Programs

Review of Lab 1Review of Lab 1

►Built-in TypesBuilt-in Types Integer typesInteger types

►No decimal pointNo decimal point►integer math-op integer yields an integerinteger math-op integer yields an integer►byte, short, int, longbyte, short, int, long

Real typesReal types►Have decimal pointHave decimal point►real math-op real yields a realreal math-op real yields a real►float, double float, double

Page 3: Introduction to Programming Writing Java Beginning Java Programs

Review of lab 1 ContinuedReview of lab 1 Continued

► Java VariablesJava Variables AttributesAttributes

►Name Name ►TypeType►ValueValue

Specifies where data is stored in memorySpecifies where data is stored in memory Java requires that a variable be declared before Java requires that a variable be declared before

it can be used.it can be used. Declaration Form:Declaration Form:

►Type variable-name;Type variable-name;►Can only declare once!Can only declare once!

Page 4: Introduction to Programming Writing Java Beginning Java Programs

Review of Lab 1 ContinuedReview of Lab 1 Continued

►Variable Naming ConventionsVariable Naming Conventions Start with letter or _ follow with any Start with letter or _ follow with any

number of letters, digits, or _number of letters, digits, or _ Names are case sensitiveNames are case sensitive Convention – variable names start with Convention – variable names start with

lower case letter.lower case letter. Names should be meaningful.Names should be meaningful.

►salessales►noItemsnoItems►qtyOnHandqtyOnHand

Camel notation

Page 5: Introduction to Programming Writing Java Beginning Java Programs

Review of Lab 1Review of Lab 1

►What is wrong?What is wrong?int firstNum = 0;int firstNum = 0;int firstNum = firstNum + 1;int firstNum = firstNum + 1;

►What does the = operator in Java mean?What does the = operator in Java mean?►What is the type of the result of What is the type of the result of

double total, price;double total, price;int amt;int amt;total = price * amt;total = price * amt;

►What is wrong withWhat is wrong withamt = total/price;amt = total/price;

Page 6: Introduction to Programming Writing Java Beginning Java Programs

The Semicolon RuleThe Semicolon Rule

►Always end a Java statement with a Always end a Java statement with a semicolon!semicolon! Be careful! The interaction pane does not Be careful! The interaction pane does not

require a semicolon after each statement.require a semicolon after each statement. In a program typed into the definition pane, In a program typed into the definition pane,

Java does.Java does. In the interaction pane, typing a semicolon In the interaction pane, typing a semicolon

after a statement does not show the value after a statement does not show the value of the result. Leaving the semicolon off of the result. Leaving the semicolon off does.does.

Page 7: Introduction to Programming Writing Java Beginning Java Programs

Object VariablesObject Variables

► Java is an Object-oriented programming Java is an Object-oriented programming language.language.

►We work mostly with objects.We work mostly with objects.►However, built-in numeric types are not However, built-in numeric types are not

objects. ie. int, float, double, …objects. ie. int, float, double, …► Strings are objects.Strings are objects.► String myName;String myName;

myName is a reference to a string objectmyName is a reference to a string object Objects must be created before they are assigned.Objects must be created before they are assigned. myName has the initial value of null (it does not myName has the initial value of null (it does not

reference a string object)reference a string object) Much more on this later.Much more on this later.

Page 8: Introduction to Programming Writing Java Beginning Java Programs

Classes and ObjectsClasses and Objects

► Classes are templates that define what Classes are templates that define what objects look like and how they behave.objects look like and how they behave.

► An object is an instantiations of a classAn object is an instantiations of a class► Class names in Java should start with a Class names in Java should start with a

capital letter.capital letter.► Turtle is a classTurtle is a class

It defines object methods that let you use a It defines object methods that let you use a Turtle object.Turtle object.

//create a turtle object from the Turtle class//create a turtle object from the Turtle class Turtle myTurtle = new Turtle(myWorld); Turtle myTurtle = new Turtle(myWorld);

Class name defines the type

Makes a new

object

Constructor: Method

that initializes a

new obj.

Page 9: Introduction to Programming Writing Java Beginning Java Programs

Object (Instance) MethodsObject (Instance) Methods

►The behavior of an object is defined by The behavior of an object is defined by the methods that belong to the method.the methods that belong to the method.

►Each instance of an object has it own Each instance of an object has it own copy of all the methods defined in the copy of all the methods defined in the object’s class that are not Class Methods.object’s class that are not Class Methods.

►Turtle turtle1 = new Turtle(myWorld);Turtle turtle1 = new Turtle(myWorld);

Turtle turtle2 = new Turtle(myWorld);Turtle turtle2 = new Turtle(myWorld);

turtle1.turnRight(); turtle2.turnRight();turtle1.turnRight(); turtle2.turnRight();

Note: both turtles have a turnRight method

Page 10: Introduction to Programming Writing Java Beginning Java Programs

Class MethodsClass Methods

►Some classes have define methods.Some classes have define methods.► java.Mathjava.Math

Class that defines math functions to useClass that defines math functions to use Would not want multiple math objects that Would not want multiple math objects that

each implement an abs method.each implement an abs method. Class methods are methods that belong to Class methods are methods that belong to

only the class and hence there is only one only the class and hence there is only one copy of the method for all objects of the copy of the method for all objects of the class.class.

int myVal = Math.abs(-12); int myVal = Math.abs(-12);

Page 11: Introduction to Programming Writing Java Beginning Java Programs

A Basic Java ProgramA Basic Java Program

// if you have to add import statements put // if you have to add import statements put //them here//them herepublic class CS1Test {public class CS1Test { public static void main(String [] args) {public static void main(String [] args) { // put you Java program statements here// put you Java program statements here }}}}►You will see what this is for in a minute.You will see what this is for in a minute.

Page 12: Introduction to Programming Writing Java Beginning Java Programs

Working With TurtlesWorking With TurtlesExample of using classesExample of using classes

►Get a world for our turtle to live inGet a world for our turtle to live in World csExWorld = new World();World csExWorld = new World();

►Put a turtle in our worldPut a turtle in our world Turtle ourTurtle = new Turtle(csExWorld);Turtle ourTurtle = new Turtle(csExWorld);

►Check the state of our turtleCheck the state of our turtle System.out.println(ourTurtle);System.out.println(ourTurtle); System.out.println(ourTurtle.toString());System.out.println(ourTurtle.toString());

Parameter that

specifies the

world to put the

turtle in.

Page 13: Introduction to Programming Writing Java Beginning Java Programs

Talking to a TurtleTalking to a Turtle

►When we want an object to do When we want an object to do something we send it a message.something we send it a message.

►Make the turtle wander aroundMake the turtle wander around ourTurtle.forward(20);ourTurtle.forward(20); ourTurtle.turnLeft();ourTurtle.turnLeft(); ourTurtle.forward(40);ourTurtle.forward(40); ourTurtle.turn(45);ourTurtle.turn(45); ourTurtle.forward(65);ourTurtle.forward(65);

Page 14: Introduction to Programming Writing Java Beginning Java Programs

How Do I Know What Turtles How Do I Know What Turtles Can Do?Can Do?

►The set of methods that define what a The set of methods that define what a class can do is called an API class can do is called an API (Application Program Interface).(Application Program Interface).

► Java defines a special format called Java defines a special format called JavaDoc for presenting APIs.JavaDoc for presenting APIs.

►You can find a link to the doc on the You can find a link to the doc on the desktop of the lab machines and at C:\desktop of the lab machines and at C:\JavaJars\intro-prog-java\bookClasses\JavaJars\intro-prog-java\bookClasses\doc\index.html.doc\index.html.

Page 15: Introduction to Programming Writing Java Beginning Java Programs

Problem: Draw a squareProblem: Draw a square► Describe how the turtle will travel in a square.Describe how the turtle will travel in a square.► Program Code:Program Code:

//draw side one//draw side oneourTurtle.forward(100);ourTurtle.forward(100);// turn 90 deg counterclockwise// turn 90 deg counterclockwiseourTurtle.turnLeft();ourTurtle.turnLeft();// draw side two// draw side twoourTurtle.forward(100);ourTurtle.forward(100);// turn 90 deg counterclockwise// turn 90 deg counterclockwiseourTurtle.turnLeft();ourTurtle.turnLeft();// draw side three// draw side threeourTurtle.forward(100);ourTurtle.forward(100);//turn 90 degrees counterclockwise//turn 90 degrees counterclockwiseourTurtle.turnLeft();ourTurtle.turnLeft();// draw side four// draw side fourourTurtle.forward(100);ourTurtle.forward(100);

Page 16: Introduction to Programming Writing Java Beginning Java Programs

Reusing CodeReusing Code

►What if we wanted to draw a second What if we wanted to draw a second square?square? We would have to retype the code a We would have to retype the code a

second time.second time. Not good! Is not there a better way?Not good! Is not there a better way?

►Define a method that draws a square. Define a method that draws a square. ►We can invoke it every time we need We can invoke it every time we need

to draw a square.to draw a square.

Page 17: Introduction to Programming Writing Java Beginning Java Programs

The drawSquare MethodThe drawSquare Method

public void drawSquare() {public void drawSquare() {//draw side one//draw side onethis.forward(100);this.forward(100);// turn 90 deg counterclockwise// turn 90 deg counterclockwisethis.turnLeft();this.turnLeft();// draw side two// draw side twothis.forward(100);this.forward(100);// turn 90 deg counterclockwise// turn 90 deg counterclockwisethis.turnLeft();this.turnLeft();// draw side three// draw side threethis.forward(100);this.forward(100);//turn 90 degrees counterclockwise//turn 90 degrees counterclockwisethis.turnLeft();this.turnLeft();// draw side four// draw side fourthis.forward(100);this.forward(100);

}}

}Body of the method

Parentheses required

Opening and Closing Brace Required

1. Open the Turtle.java file found in C:\intro-prog-java\bookClasses

2. Put the method definition at the bottom of the class where the documentation directs.

3. Create a World, a Turtle, and draw a square.

Page 18: Introduction to Programming Writing Java Beginning Java Programs

How do we draw two How do we draw two squares?squares?

► Call drawSquare() twice.Call drawSquare() twice.► What happened?What happened?► Cannot call drawSquare again it will draw Cannot call drawSquare again it will draw

over top the square we have drawn.over top the square we have drawn.► Need to move the Turtle before we draw Need to move the Turtle before we draw

again. again. ► How? Look at documentationHow? Look at documentation

Pen upPen up Move to new positionMove to new position Pen downPen down

Page 19: Introduction to Programming Writing Java Beginning Java Programs

ParametersParameters

►How do we draw squares of different sizes?How do we draw squares of different sizes?►Observation: Each time we draw a square we Observation: Each time we draw a square we

need to change the 100 to the size we want.need to change the 100 to the size we want.► This could generate a lot of almost identical This could generate a lot of almost identical

methods.methods.► Use a parameter to specify the width.Use a parameter to specify the width.

public void drawSquare(int width) { … }public void drawSquare(int width) { … } Change 100 to widthChange 100 to width

► Call as:Call as: ourTurtle.drawSquare(50);ourTurtle.drawSquare(50);

Page 20: Introduction to Programming Writing Java Beginning Java Programs

Draw the squares in Different Draw the squares in Different ColorsColors

►Back to the documentationBack to the documentation public void public void setColorsetColor(java.awt.Color color) (java.awt.Color color) Need a Color object found in java.awt packageNeed a Color object found in java.awt package Must import this package to use itMust import this package to use it Find information in Java 1.5 API DocumentationFind information in Java 1.5 API Documentation

► InvokeInvoke ourTurtle.setColor(Color.BLUE);ourTurtle.setColor(Color.BLUE); Draw a blue square.Draw a blue square.

Page 21: Introduction to Programming Writing Java Beginning Java Programs

How do you …?How do you …?

►Save the program?Save the program? Put it in a CSTurtleTest classPut it in a CSTurtleTest class

►Hide the turtle?Hide the turtle?►Draw the squares at an angle to the Draw the squares at an angle to the

window?window?