Introduction to Programming Writing Java Beginning Java Programs

Embed Size (px)

Text of Introduction to Programming Writing Java Beginning Java Programs

  • Introduction to ProgrammingWriting Java Beginning Java Programs

  • Review of Lab 1Built-in TypesInteger typesNo decimal pointinteger math-op integer yields an integerbyte, short, int, longReal typesHave decimal pointreal math-op real yields a realfloat, double

  • Review of lab 1 ContinuedJava VariablesAttributesName TypeValueSpecifies where data is stored in memoryJava requires that a variable be declared before it can be used.Declaration Form:Type variable-name;Can only declare once!

  • Review of Lab 1 ContinuedVariable Naming ConventionsStart with letter or _ follow with any number of letters, digits, or _Names are case sensitiveConvention variable names start with lower case letter.Names should be meaningful.salesnoItemsqtyOnHand

    Camel notation

  • Review of Lab 1What is wrong?int firstNum = 0;int firstNum = firstNum + 1;What does the = operator in Java mean?What is the type of the result of double total, price;int amt;total = price * amt;What is wrong withamt = total/price;

  • The Semicolon RuleAlways end a Java statement with a semicolon!Be careful! The interaction pane does not require a semicolon after each statement.In a program typed into the definition pane, Java does.In the interaction pane, typing a semicolon after a statement does not show the value of the result. Leaving the semicolon off does.

  • Object VariablesJava is an Object-oriented programming language.We work mostly with objects.However, built-in numeric types are not objects. ie. int, float, double, Strings are objects.String myName;myName is a reference to a string objectObjects must be created before they are assigned.myName has the initial value of null (it does not reference a string object)Much more on this later.

  • Classes and ObjectsClasses are templates that define what objects look like and how they behave.An object is an instantiations of a classClass names in Java should start with a capital letter.Turtle is a classIt defines object methods that let you use a Turtle object.//create a turtle object from the Turtle class Turtle myTurtle = new Turtle(myWorld);

    Class name defines the typeMakes a new objectConstructor: Method that initializes a new obj.

  • Object (Instance) MethodsThe behavior of an object is defined by the methods that belong to the method.Each instance of an object has it own copy of all the methods defined in the objects class that are not Class Methods.Turtle turtle1 = new Turtle(myWorld);Turtle turtle2 = new Turtle(myWorld);turtle1.turnRight(); turtle2.turnRight();Note: both turtles have a turnRight method

  • Class MethodsSome classes have define that defines math functions to useWould not want multiple math objects that each implement an abs method.Class methods are methods that belong to only the class and hence there is only one copy of the method for all objects of the myVal = Math.abs(-12);

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

  • Working With TurtlesExample of using classesGet a world for our turtle to live inWorld csExWorld = new World();Put a turtle in our worldTurtle ourTurtle = new Turtle(csExWorld);Check the state of our turtleSystem.out.println(ourTurtle);System.out.println(ourTurtle.toString());Parameter that specifies the world to put the turtle in.

  • Talking to a TurtleWhen we want an object to do something we send it a message.Make the turtle wander aroundourTurtle.forward(20);ourTurtle.turnLeft();ourTurtle.forward(40);ourTurtle.turn(45);ourTurtle.forward(65);

  • How Do I Know What Turtles Can Do?The set of methods that define what a class can do is called an API (Application Program Interface).Java defines a special format called JavaDoc for presenting APIs.You can find a link to the doc on the desktop of the lab machines and at C:\JavaJars\intro-prog-java\bookClasses\doc\index.html.

  • Problem: Draw a squareDescribe how the turtle will travel in a square.Program Code://draw side oneourTurtle.forward(100);// turn 90 deg counterclockwiseourTurtle.turnLeft();// draw side twoourTurtle.forward(100);// turn 90 deg counterclockwiseourTurtle.turnLeft();// draw side threeourTurtle.forward(100);//turn 90 degrees counterclockwiseourTurtle.turnLeft();// draw side fourourTurtle.forward(100);

  • Reusing CodeWhat if we wanted to draw a second square?We would have to retype the code a second time.Not good! Is not there a better way?Define a method that draws a square. We can invoke it every time we need to draw a square.

  • The drawSquare Methodpublic void drawSquare() {//draw side onethis.forward(100);// turn 90 deg counterclockwisethis.turnLeft();// draw side twothis.forward(100);// turn 90 deg counterclockwisethis.turnLeft();// draw side threethis.forward(100);//turn 90 degrees counterclockwisethis.turnLeft();// draw side fourthis.forward(100);}}Body of the methodParentheses requiredOpening and Closing Brace RequiredOpen the file found in C:\intro-prog-java\bookClasses Put the method definition at the bottom of the class where the documentation directs.Create a World, a Turtle, and draw a square.

  • How do we draw two squares?Call drawSquare() twice.What happened?Cannot call drawSquare again it will draw over top the square we have drawn.Need to move the Turtle before we draw again. How? Look at documentationPen upMove to new positionPen down

  • ParametersHow do we draw squares of different sizes?Observation: Each time we draw a square we need to change the 100 to the size we want.This could generate a lot of almost identical methods.Use a parameter to specify the width.public void drawSquare(int width) { }Change 100 to widthCall as:ourTurtle.drawSquare(50);

  • Draw the squares in Different ColorsBack to the documentationpublic void setColor(java.awt.Colorcolor) Need a Color object found in java.awt packageMust import this package to use itFind information in Java 1.5 API DocumentationInvokeourTurtle.setColor(Color.BLUE);Draw a blue square.

  • How do you ?Save the program?Put it in a CSTurtleTest classHide the turtle?Draw the squares at an angle to the window?