TeachScheme, ReachJava Adelphi University Thursday morning June 25, 2009.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

CSC 270 Nov. 22, 2005 Last Day of Scheme Dr. Stephen Bloch
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
Lecture 1: Comments, Variables, Assignment. Definitions The formal (human-readable) instructions that we give to the computer is called source code The.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Week 2: Primitive Data Types 1.  Programming in Java  Everything goes inside a class  The main() method is the starting point for executing instructions.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Introduction to Primitives. Overview Today we will discuss: –The eight primitive types, especially int and double –Declaring the types of variables –Operations.
Writing methods and Java Statements. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables.
Chapter 2 storing numbers and creating objects Pages in Horstmann.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Methods: a first introduction Two ways to make tea: 1: boil water; put teabag into cup;... etc : tell your younger brother: makeTea(1 milk, 0 sugar);
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Mr. Wortzman. Tabs (Block Categories) Available Blocks Script Area Sprite Stage All sprites in this project.
TeachScheme, ReachJava Adelphi University Tuesday afternoon June 23, 2009.
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
TeachScheme, ReachJava Adelphi University Monday afternoon July 12, 2010.
TeachScheme, ReachJava Adelphi University Tuesday morning July 13, 2010.
Introduction to Python
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
TeachScheme, ReachJava Adelphi University Tuesday afternoon July 13, 2010.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Classes CS 21a: Introduction to Computing I First Semester,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
TeachScheme, ReachJava Adelphi University Thursday afternoon July 15, 2010.
TeachScheme, ReachJava Adelphi University Friday morning July 16, 2010.
PART 1 Part 1: The Material. Whether you knew it or not, all the programming that you have performed until now was in the boundaries of procedural programming.
Chapter 3 Object Interaction.  To construct interesting applications it is not enough to build individual objects  Objects must be combined so they.
Newport Robotics Group 1 Tuesdays, 6:30 – 8:30 PM Newport High School Week 4 10/23/2014.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Python Let’s get started!.
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
CS 5JA Introduction to Java Graphics One of the powerful things about Java is that there is.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
A Sample Program #include using namespace std; int main(void) { cout
INTRODUCTION Java is a true OO language the underlying structure of all Java programs is classes. Everything must be encapsulated in a class that defines.
Chapter 2 Basic Computation
Introduction to Computer Science / Procedural – 67130
Variables and Primative Types
Lesson 2: Building Blocks of Programming
Stacks.
Java Classes and Objects 3rd Lecture
Stacks.
Barb Ericson Georgia Institute of Technology June 2005
Introduction to Primitives
Introduction to Primitives
Unit 3: Variables in Java
Barb Ericson Georgia Institute of Technology Oct 2005
Just Enough Java 17-May-19.
Presentation transcript:

TeachScheme, ReachJava Adelphi University Thursday morning June 25, 2009

The Transition to Java Goals: Teach enough [good] Java and OOP that students can use it in subsequent courses Maintain lessons learned about specification, testing, data types, etc. Teach techniques & idioms common to Java that haven’t been covered in Scheme (e.g. loops)

Development environments ProfessorJ: Java subset in DrScheme –doesn't have a lot of expected features (System.out.println, assert, generics, collection classes…) DrJava: DrScheme's cousin –more complete Java; familiar user interface with Definitions and Interactions panes BlueJ –larger user community, more support –automatic class diagrams –also has "CodePad", like Interactions pane –I'll use BlueJ this week

Expressions in Java: arithmetic Infix notation for arithmetic Order of operations Does 3+4*5 mean (3+4)*5, or 3+(4*5)? PEMDAS: 3+(4*5) Associativity Does mean (3-4)-5, or 3-(4-5)? Left associativity: (3-4)-5 Operations on integers produce integers Even division? Yes: 5/3 = 1

Expressions in Java: Strings "abc" as in Scheme "abc"+"def"returns "abcdef" (equivalent to string-append in Scheme) "abc"-"def"meaningless 3 + " years"returns "3 years" 4+5+" years"returns "9 years" "I'm "+4+5+" years old" returns "I'm 45 years old"… huh? Left associativity!

Variables in Java int age = 45; "I'm " + age + " years old" String name = "Chris"; "My friend's name is " + name name + " is " + age + " years old" General syntax rule: type varname = expression ;

More numeric expressions in Java Math. method-name (args) Math.sqrt(2)returns 1.414… Math.cos(Math.PI)returns -1.0 Math.max(3, -4)returns 3 … lots of built-in mathematical functions … Analogous to Scheme function calls from a "library" named Math

More String expressions in Java expression. method-name (args) "abc".length()returns 3 "abc".toUpperCase()returns "ABC" "abc".concat("def")returns "abcdef" "abcde".substring(1)returns "bcde" "abcde".substring(1,3)returns "bc" "abcde".indexOf("d")returns 3 "hello everybody".replaceAll("y","fnord") returns "hello everfnordbodfnord"

More String expressions in Java expression. method-name (args) These too are analogous to Scheme function calls, but the expression in front is one of the arguments to the function (string-append "hello" "goodbye") becomes "hello".concat("goodbye") (string-length "hello") becomes "hello".length()

Two kinds of methods "static" methods called with a class name in front of the dot "non-static" methods called with an expression in front of the dot We'll learn to write both eventually. "static" first.

Exercises Write a Java expression using the int variable age and producing something like "I am ___ years old; next year I'll be ___." Write a Java expression using the String variable name and producing something like "Hi, __! There are __ letters in your name."

Writing functions in Java "function" in Scheme = "method" in Java All method definitions must be inside a class To create a class, select "New Class", and fill in a class name (say, June25). Class names cannot contain spaces or punctuation, and should usually start with a capital letter. BlueJ gives you a bunch of boilerplate code. You can ignore it, or delete everything between the first "{" and the last "}".

Writing methods in Java public static String greet (String name) { return "Hello, " + name + "!"; } analogous to (define (greet name) (string-append "Hello, " name "!")) Note: you have to declare the types of parameters and methods in Java. "String" must be capitalized. The "public" is boilerplate; I'll explain later. The "static" means this method will be called with the class name (June25) in front of the dot.

Testing manually Type June25.greet("Steve") in the CodePad. It should return "Hello, Steve!". Try some other examples.

Testing automatically 1)right-click on the class in the diagram and select "Create Test Class" 2)double-click the new class (June25Test) 3)This is where we'll put all the test cases for June25. 4)find the "testSomething" method and rename it "testGreet" 5)inside it, put the line t.checkExpect (June25.greet("Steve"), "Hello, Steve!"); 6)Click the "Compile" button. If it doesn't complain… 7)right-click the test class and select "testEverything". Try adding some more tests, including some that fail.

The design recipe in Java Contract (in June25 class): // static greet : String -> String Test cases (in June25Test class): public void testGreet (Tester t) { t.checkExpect (June25.greet("Steve"), "Hello, Steve!"); t.checkExpect (June25.greet("Albert Einstein"), "Hello, Albert Einstein!"); }

The design recipe in Java Skeleton (in June25 class): public static String greet (String name) { }

The design recipe in Java Inventory: public static String greet (String name) { // nameString }

The design recipe in Java Body: public static String greet (String name) { // nameString return "Hello, " + name + "!"; }

The design recipe in Java Testing: Hit the "Compile" button If it complains, fix the errors and try again. If not, right-click on "June25Test" and select "testEverything". Read the report.

Exercises Write a static method greet2 that takes in a String parameter and returns something like "Hi, __! There are __ letters in your name." Follow the design recipe.

Writing methods on numbers Write a cube method on integers. Contract: // static cube : integer -> integer Test cases (in June25Test class): public void testCube (Tester t) { t.checkExpect (June25.cube(0), 0); t.checkExpect (June25.cube(4), 64); t.checkExpect (June25.cube(-5), -125); }

Writing methods on numbers Skeleton: public static int cube (int x) { } Note: Java has no "number" type; you have to decide between "int", for integers, and "double", for any other number.

Writing methods on numbers Inventory: public static int cube (int x) { // xint }

Writing methods on numbers Body: public static int cube (int x) { // xint return x * x * x; } Test as before.

Inexact numbers Write a static method circPerim that takes in the radius of a circle and returns its perimeter. Contract: // circPerim : double -> double Test cases (in June25Test): public void testCircPerim (Tester t) { t.checkInexact (June25.circPerim(0.0), 0.0, 0.01); t.checkInexact (June25.circPerim(1.0), 6.28, 0.01); }

Inexact numbers Skeleton, inventory, body: public static double circPerim (double radius) { // radiusdouble return radius * 2 * Math.PI; } Test as before.

Exercises Write a static method avgThree which takes in three double numbers and returns their average. Write a static method convert3digits which takes in three integers representing the "hundreds", "tens", and "ones" digits of a number, and returns the number. Write a static method largestRoot which takes in three double numbers a, b, and c, and returns (-b+ sqrt (b2-4ac))/(2a).

Booleans Write a static method canVote which takes in a person's age and returns whether the person is at least 18 years old. Contract (in June25 class): // static canVote : int -> boolean Test cases (in June25Test class): public void testCanVote (Tester t) { t.checkExpect (June25.canVote(17), false); t.checkExpect (June25.canVote(18), true); t.checkExpect (June25.canVote(19), true); }

Booleans Skeleton, inventory, body (in June25 class): public static boolean canVote (int age) { // ageint // 18fixed int return age >= 18; }

Boolean operators Scheme (and foo bar) (or foo bar) (not foo) Java foo && bar foo || bar ! foo

Conditionals Scheme (cond [q1 a1] [q2 a2] [q3 a3]) Java if (q1) return a1; else if (q2) return a2; else if (q3) return a3;

Definition by choices Definition by choices within a single type (String, int, double, etc.) is done by conditionals. Definition by choices between types is done differently (see below)

Exercises Write a static method teenager that takes in an age and returns true if it's between 13 and 19 inclusive Write a static method roughAge that takes in an age and returns either "child", "teenager", or "adult" as appropriate

Definition by parts In Scheme… ;; A Book is (make-book String String Number) (define-struct book (title author pub-year)) ;; examples (define alice (make-book "Alice in Wonderland" "Carroll" 1866)) (define glass (make-book "TTLG" "Carroll" 1872)) (define cat-hat (make-book "The Cat in the Hat" "Seuss" 1957))

The same thing in Java // to represent a book in the library class Book { String title; String author; int pubYear; // other stuff goes in here }

About the "other stuff"… In Scheme, we got a constructor, getters, and discriminator "for free": ; make-book : string string number -> book ; book-title : book -> string ; book-author : book -> string ; book-pub-year: book -> number ; book? : anything -> book

About the "other stuff"… In Java, we have to write a constructor. Getters are free (I'm lying). We'll come back to discriminators. Constructor (inside Book class): public Book (String title, String author, int pubYear) { this.title = title; this.author = author; this.pubYear= pubYear; } Note: title is the name of a parameter; this.title is the name of a struct field. A constructor looks sorta like a method, but it's not static, its return type is the class it's in, and it has no name at all.

Making examples in Java Book alice = new Book("Alice", "Carroll", 1866); Book glass = new Book("TTLG", "Carroll", 1872); Book catHat = new Book("The Cat in the Hat", "Seuss", 1957);

Using examples in CodePad alice.title // should return "Alice" glass.author // should return "Carroll" catHat.pubYear // should return 1957 Same syntax that we used in constructor to refer to the fields.

Using examples in test class class BookTest { Book alice = new Book("Alice", "Carroll", 1866); Book glass = new Book("TTLG", "Carroll", 1872); Book catHat = new Book("The Cat in the Hat", "Seuss", 1957); … public void testFields (Tester t) { t.checkExpect (this.alice.title, "Alice"); t.checkExpect (this.glass.author, "Carroll"); t.checkExpect (this.catHat.cnum, 1957); }

Exercises Write a Java class Date with three integer fields day, month, and year, a constructor, and examples. Write a Java class Posn with two double fields x and y, a constructor, and examples.

Time check Snack break?

Non-static methods Write a non-static method age which operates on a Book, takes in the current year, and returns how many years old the book is. Contract: // age : int -> int Test cases (in BookTest class): public void testAge (Tester t) { t.checkExpect (this.alice.age(2009), 143); t.checkExpect (this.glass.age(2009), 137); t.checkExpect (this.catHat.age(2009), 52); }

Non-static methods Note that a non-static method has one "special" parameter (the "receiver"), passed in front of the dot, and possibly some others in between the parentheses. A non-static method with 3 parameters (plus the "receiver") corresponds to a Scheme function or a static method with 4 parameters Many non-static methods take no parameters at all, getting all the information they need from the receiver. age actually takes in a Book (as the receiver) and an int (as a parameter).

Methods in data classes Skeleton (in Book class): public int age (int currentYear) { }

Methods in data classes Inventory public int age (int currentYear) { // currentYearint // thisBook // this.titleString // this.authorString // this.pubYearint } Note: The inventory for a non-static method always includes this; its type is always whatever class it's in.

Methods in data classes Body public int age (int currentYear) { // currentYearint // thisBook // this.titleString // this.authorString // this.pubYearint return currentYear – this.pubYear; }

A standard method: toString Write a non-static method toString that operates on a Book and combines all the information about it into one readable String. Contract (in Book class): // toString : nothing -> String Test cases (in BookTest class): public void testToString (Tester t) { t.checkExpect (this.alice.toString(), "Alice, by Carroll, published 1866"); t.checkExpect (this.glass.toString(), "TTLG, by Carroll, published 1872"); t.checkExpect (this.catHat.toString(), "The Cat in the Hat, by Seuss, published 1957"); }

A standard method: toString Skeleton, inventory, body (in Book class): public String toString () { // thisBook // this.titleString // this.authorString // this.pubYearint return this.title + ", by " + this.author + ", published " + this.pubYear; }

Exercises Add toString methods to the Date and Posn classes. Add a method distanceToOrigin, operating on a Posn and taking no parameters. Add a method swapCoords, operating on a Posn and taking no parameters; it returns a new Posn like this one but with x & y reversed.

Exercises Add a method dayInYear that operates on a Date, takes no parameters, and returns the number of days since the beginning of the year. (For simplicity, assume all months are 30 days long.) Add a method distance that operates on a Posn, takes in another Posn, and returns the Euclidean distance between them.

Time check lunch time?

Class composition Define a class LogEntry to represent a runner's daily log. It contains the Date of the run, the distance in miles, the time in minutes, and a free-form comment. Include a constructor several examples a toString method an avgSpeed method an addComment method (which takes in a String and returns a LogEntry just like the old one but with the String added onto whatever comments were already there).

Class composition Define a class Circle to represent a circle on the screen. It contains a center (of type Posn), a radius (double), and a color (String). Include a constructor several examples a toString method an area method a contains method that takes in another Posn and returns a boolean indicating whether that Posn is inside the circle a scale method that takes in a double scaling factor and returns a new Circle like this one but with the radius multiplied by the scaling factor.

Class composition Define a class Rectangle to represent a rectangle on the screen. It contains a top-left corner (of type Posn), a width and height (both double), and a color (String). Include a constructor several examples a toString method an area method a contains method that takes in another Posn and returns a boolean indicating whether that Posn is inside the rectangle a scale method that takes in a double scaling factor and returns a new Circle like this one but with the width and height multiplied by the scaling factor.

Definition by choices Define a data type Shape which is either a Circle or a Rectangle. Since Circle and Rectangle both have constructors, Shape doesn't need one.

Definition by choices interface Shape { } … class Circle implements Shape { … }

interface Shape { } class Circle implements Shape { Posn center; double radius; String color; … } class Rectangle implements Shape { Posn topLeft; double width; double height; String color; … }

What can you do with this? A variable of type Shape can hold either a Circle or a Rectangle: Shape shape1 = new Circle (new Posn(3,4),5,"blue"); Shape shape2 = new Rectangle (new Posn (50,20), 30, 40, "orange");

What can't you do with this? shape1.area() doesn't compile! Why not? In Java, every variable has two types: the static type from its declaration, and the dynamic type from what it actually contains. shape1 was declared as a Shape, so that's its static type. Static type is used to decide what's a legal call and what isn't.

To fix this… interface Shape { public double area (); public boolean contains (Posn other); public Shape scale (double factor); }

What can you do with this? Now you can call the area, contains, and scale methods on a Shape variable shape1.area() // should return c shape2.area() // should return 1200 shape1.scale(2.0) // should return // new Circle(new Posn(3,4), 10, "blue") etc.

time check

Lists in Java A StringList is either an EmptyStringList or a NonEmptyStringList (ESL or NESL for short). An ESL has no parts. A NESL has two parts: first (a String) and rest (a StringList).

Lists in Java Write classes ESL and NESL, and interface StringList. For each class, provide a constructor examples a toString method

Lists in Java Write the following methods on StringLists: countStrings : nothing -> int contains : String -> boolean countMatches : String -> int

Are we done yet? Fill out end-of-day survey Eat Go home Sleep Come back for another day