Presentation is loading. Please wait.

Presentation is loading. Please wait.

TeachScheme, ReachJava Adelphi University Thursday afternoon July 15, 2010.

Similar presentations


Presentation on theme: "TeachScheme, ReachJava Adelphi University Thursday afternoon July 15, 2010."— Presentation transcript:

1 TeachScheme, ReachJava Adelphi University Thursday afternoon July 15, 2010

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

3 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

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

5 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!

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

7 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

8 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"

9 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()

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

11 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."

12 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, July15). 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 "}".

13 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 (July15) in front of the dot.

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

15 Testing automatically 1)right-click on the class in the diagram and select "Create Test Class" 2)double-click the new class (July15Test) 3)This is where we'll put all the test cases for July15. 4)find the "testSomething" method and rename it "testGreet" 5)inside it, put the line t.checkExpect (July15.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.

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

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

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

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

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

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

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

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

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

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

26 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 July15Test): public void testCircPerim (Tester t) { t.checkInexact (July15.circPerim(0.0), 0.0, 0.01); t.checkInexact (July15.circPerim(1.0), 6.28, 0.01); }

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

28 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 (b 2 -4ac))/(2a).

29 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 July15 class): // static canVote : int -> boolean Test cases (in July15Test class): public void testCanVote (Tester t) { t.checkExpect (July15.canVote(17), false); t.checkExpect (July15.canVote(18), true); t.checkExpect (July15.canVote(19), true); }

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

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

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

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

34 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

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

36 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 }

37 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

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

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

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

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

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

43 Time check Snack break?

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

45 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).

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

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

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

49 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"); }

50 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; }

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

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

53 Time check


Download ppt "TeachScheme, ReachJava Adelphi University Thursday afternoon July 15, 2010."

Similar presentations


Ads by Google