Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
CSE 142 Lab 9: Inheritance; Final Exam Practice University of Washington, CSE 142 Lab 9: Inheritance; Final Exam Practice University of Washington, CSE 142 Lab 9: Inheritance; Final Exam Practice Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp. lab document created by Marty Stepp, Stuart Reges and Whitaker Brand Basic lab instructions Talk to your classmates for help. You can even work on the lab with a partner if you like. You may want to bring your textbook to future labs to look up syntax and examples. Stuck? Confused? Have a question? Ask a TA for help, or look at the book or past lecture slides. Complete as many problems as you can within the allotted time. You don't need to keep working on these exercises after you leave the lab. Feel free to complete problems in any order. Before you leave today, make sure to check in with one of the TAs in the lab to get credit for your work. Today's lab Goals for today: use inheritance to create hierarchies of related classes extend behavior and override existing behavior practice reading and writing Critter classes practice problems similar to those that will be seen on the final exam Where you see this icon, you can click it to check the problem in Practice-It! Inheritance (syntax) public class ClassName extends SuperClass { ... } a subclass inherits all of the superclass's behavior and can override methods. To call an overridden method from the superclass, use the super keyword: super.methodName(parameters); Exercise : Car and Truck public class Car { public void m1() { System.out.println("car 1"); } public void m2() { System.out.println("car 2"); } public String toString() { return "vroom"; } } public class Truck extends Car { public void m1() { System.out.println("truck 1"); } } What is the output from the following code? Truck mycar = new Truck(); System.out.println(mycar); // vroom mycar.m1(); // truck 1 mycar.m2(); // car 2 Exercise : Car and Truck revisited public class Car { public void m1() { System.out.println("car 1"); } public void m2() { System.out.println("car 2"); } public String toString() { return "vroom"; } } public class Truck extends Car { public void m1() { System.out.println("truck 1"); } public void m2() { super.m1(); } public String toString() { return super.toString() + super.toString(); } } Suppose the Truck code changes as shown above. What is the output now? Truck mycar = new Truck(); System.out.println(mycar); // vroomvroom mycar.m1(); // truck 1 mycar.m2(); // car 1 Exercise : MonsterTruck Download the following files from the previous exercise and open them in jGRASP: Car.java, Truck.java, AutoMain.java Write a class MonsterTruck that has the behavior below. Test by running AutoMain. Some methods produce 2 lines of output; the split between lines is indicated by a /. Don't just print/return the output; if possible, use inheritance to reuse behavior from the superclass. MonsterTruck bigfoot = new MonsterTruck(); bigfoot.m1(); // monster 1 bigfoot.m2(); // truck 1 / car 1 System.out.println(bigfoot); // monster vroomvroom Employee class hierarchy Recall the inheritance hierarchy of employee classes shown in lecture. Each type of employee extends a common base class Employee and has the methods getHours, getSalary, getVacationDays, and getVacationForm. For the next several exercises you will add classes to this inheritance hierarchy. To do this, either solve the problems in Practice-It!, or download each of these files to your machine: Employee, Secretary, Lawyer, and LegalSecretary. Exercise : Marketer Write an employee class Marketer to accompany the other employees. Marketers make $50,000 ($10,000 more than general employees), and they have an additional method named advertise that prints "Act now, while supplies last!" Use the super keyword to interact with the Employee superclass as appropriate. Exercise : Janitor Write an employee class Janitor to accompany the other employees. Janitors work twice as many hours (80 hours/week), they make $30,000 ($10,000 less than others), they get half as much vacation (only 5 days), and they have an additional method named clean that prints "Workin' for the man." Use the super keyword to interact with the Employee superclass as appropriate. Exercise : HarvardLawyer Write an employee class HarvardLawyer to accompany the other employees. Harvard lawyers are like normal lawyers, but they make 20% more money than a normal lawyer, they get 3 days more vacation, and they have to fill out four of the lawyer's forms to go on vacation. That is, the getVacationForm method should return "pinkpinkpinkpink". (If the normal Lawyer's vacation form ever changed, the HarvardLawyer's should as well. For example, if Lawyer's vacation form changed to "red", the HarvardLawyer's should return "redredredred".) Use the super keyword to interact with the Employee superclass as appropriate. Critters (syntax) import java.awt.*; public class ClassName extends Critter { fields, constructors... public boolean eat() { ... } public Attack fight(String opponent) { ... } public Color getColor() { ... } public Direction getMove() { ... } public String toString() { ... } } Example Critter class: Cougar.java Exercise : Skunk errors The following critter ( Skunk.java ) is an attempt to make a critter that goes W, W, N and repeats, unless he eats food, in which case he will start going W, W, S. But the file contains errors. Download it and fix the errors so it compiles/runs properly. Test it in CritterMain and Practice-It. public class Skunk extend Critter { private int moves; private boolean hungry; public void Skunk() { // constructor hungry = false; } public static boolean eat() { hungry = true; return true; } public Direction getmoves() { moves++; if (moves >= 3) { moves = 0; } if (moves == 1 && moves == 2) { return Direction.WEST; } else if (hungry) { return Direction.NORTH; } else if (!hungry) { return Direction.SOUTH; } } } Exercise : Butterfly Write a class Butterfly that extends the Critter class, along with its movement behavior. All unspecified aspects of Butterfly use the default behavior. A Butterfly should be yellow in color. Its toString should alternate between being an x character and a - character each move. A Butterfly flies upward in the following pattern: N, W, N, E, repeat. Solve this program in jGRASP using the CritterMain simulator. Test it in Practice-it. Final exam review The CSE 142 final exam is usually very similar to the format of the practice exams. The following kinds of problems will be on your final exam: array simulation reference mystery inheritance mystery programming with Scanner (file I/O; Ch. 6) programming with arrays (Ch. 7) programming with Critters (Ch. 9) Feel free to skip ahead to the types of problems on which you need the most practice. Exercise : Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type (e.g., 7.0 rather than 7 for a double, Strings in quotes). 1 + 9 / 2 * 2.0 9.0 5.0 / (3125 % 2) + 2 * (5 / 3) 7.0 6 % 17 + 9 % 3 + 22 / 4 / 2.0 8.5 "[" + 2 + 4 * 2.0 + "]" + 3 "[28.0]3" !(3 < 2) && (4.3 > 3 || 3 < 2) true Exercise : array simulation Consider the following method: public static void mystery(int[] list) { for (int i = 0; i < list.length; i++) { list[i] = i * list[i]; } } In the left-hand column below are specific lists of integers. Indicate in the right-hand column what values would be stored in the list after method mystery executes if the integer list in the left-hand column is passed to it as a parameter. {} {} {7} {0} {3, 2} {0, 2} {5, 4, 3} {0, 4, 6} {2, 4, 6, 8} {0, 4, 12, 24} Exercise : reference mystery What four lines of output are produced by the following program? public class ReferenceMystery { public static void main(String[] args) { int y = 1; int x = 3; int[] a = new int[4]; mystery(a, y, x); // 2 3 [0, 0, 17, 0][^0-9,]+ System.out.println(x + " " + y + " " + Arrays.toString(a)); // 3 1 [0, 0, 17, 0][^0-9,]+ x = y - 1; mystery(a, y, x); // 1 0 [17, 0, 17, 0][^0-9,]+ System.out.println(x + " " + y + " " + Arrays.toString(a)); // 0 1 [17, 0, 17, 0][^0-9,]+ } public static void mystery(int[] a, int x, int y) { if (x < y) { x++; a[x] = 17; } else { a[y] = 17; } System.out.println(x + " " + y + " " + Arrays.toString(a)); } } Exercise : inheritance mystery Assume the following classes have been defined: public class A extends B { public void method2() { System.out.println("a 2"); } } public class D extends B { public void method1() { System.out.println("d 1"); } } public class C { public String toString() { return "c"; } public void method1() { System.out.println("c 1"); } public void method2() { System.out.println("c 2"); } } public class B extends C { public String toString() { return "b"; } public void method2() { System.out.println("b 2"); } } continued on the next slide... Exercise - inheritance mystery b c 1 a 2 b c 1 b 2 c c 1 c 2 b d 1 b 2 Consider the code below that uses these classes. Write each line of its output in the boxes at right. C[] elements = {new A(), new B(), new C(), new D()}; for (int i = 0; i < elements.length; i++) { System.out.println(elements[i]); elements[i].method1(); elements[i].method2(); } Exercise : inheritance mystery 2 Assume the following classes have been defined: public class Denny extends John { public void method1() { System.out.print("denny 1 "); } public String toString() { return "denny " + super.toString(); } } public class Cass { public void method1() { System.out.print("cass 1 "); } public void method2() { System.out.print("cass 2 "); } public String toString() { return "cass"; } } public class Michelle extends John { public void method1() { System.out.print("michelle 1 "); } } public class John extends Cass { public void method2() { method1(); System.out.print("john 2 "); } public String toString() { return "john"; } } continued on the next slide... Exercise - inheritance mystery 2 cass 1 cass 2 cass denny 1 denny 1 john 2 denny john cass 1 cass 1 john 2 john michelle 1 michelle 1 john 2 john Consider the code below that uses these classes. Write each line of its output in the boxes at right. Cass[] elements = {new Cass(), new Denny(), new John(), new Michelle()}; for (int i = 0; i < elements.length; i++) { elements[i].method1(); System.out.println(); elements[i].method2(); System.out.println(); System.out.println(elements[i]); System.out.println(); } Exercise : printStrings Write a method called printStrings that takes as a parameter a Scanner holding a sequence of integer/string pairs and that prints to System.out one line of output for each pair with the given string repeated the given number of times. You should solve this problem in Practice-It! Exercise : isAllEven Write a method called isAllEven that takes an array of integers as a parameter and that returns whether or not all of the values are even numbers (true for yes, false for no). You should solve this problem in Practice-It! Exercise : longestSortedSequence Write a method called longestSortedSequence that accepts an array of integers as a parameter and that returns the length of the longest sorted (nondecreasing) sequence of integers in the array. You should solve this problem in Practice-It! Date class Suppose you are given a class named Date with the following contents: // A Date stores a month and day of the (non-leap) year. public class Date { private int month; private int day; // constructs a new Date with the given month/day public Date(int m, int d) // returns the fields' values public int getMonth() public int getDay() public int daysInMonth() public void nextDay() public String toString() ... } Exercise : Date daysTillXmas Write an instance method daysTillXmas that will be placed inside the Date class. The method returns how many days away the Date object is from Christmas, December 25, in the same year. For example, Nov. 22 is 33 days away, Sep. 3 is 113 days away, Dec 25 is 0 days away, and Dec 31 is -6 days away. Here is an example call: Date d = new Date(9, 3); System.out.println(d.daysTillXmas()); // 113 Test your solution to this problem in Practice-It. Exercise : Hyena Write a class Hyena that extends the Critter class, along with its movement behavior. All unspecified aspects of Hyena use the default behavior. A Hyena object moves in a rectangular pattern looking for food, walking NORTH, then EAST, then SOUTH, then WEST. Each time the hyena walks an entire rectangle, it starts the rectangle pattern over again but with a rectangle 1 step wider than before. The general pattern is as follows: N, E, S, W, N, E, E, S, W, W, N, E, E, E, S, W, W, W, N, E, E, E, E, S, W, W, W, W, ... Solve this program in jGRASP using the CritterMain simulator. Exercise : Hyena revisited Modify your Hyena class from the previous problem to add eating behavior. If the hyena encounters food at any point during its movement pattern, it eats the food and starts the pattern over, lengthening the rectangular pattern by 1 in the process. For example: N, E, S, W, N, E, E (eats food), N, E, E, E, S, W, W (eats food), N, E, E, E, E, S, W, W, W, W, N, E, E, E, E, E, S (eats food), N, E, E, E, E, E, E, S, W, W, ... Solve this program in jGRASP with CritterMain, then test it using the Practice-it link above. Exercise : Expressions For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type (e.g., 7.0 rather than 7 for a double, Strings in quotes). 12/5 + 8/4 4 2.5 * 2 + 17/4 9.0 41 % 15 % 7 + 17 % 3 6 21/2 + "7 % 3" + 17 % 4 "107 % 31" 46/3/2.0/3 * 4/5 2.0 Exercise : array simulation Consider the following method: public static void arrayMystery(int[] a) { for (int i = 1; i < a.length - 1; i++) { a[i] = a[i - 1] - a[i] + a[i + 1]; } } In the left-hand column below are specific lists of integers. Indicate in the right-hand column what values would be stored in the list after method mystery executes if the integer list in the left-hand column is passed to it as a parameter. {42, 42} {42, 42} {6, 2, 4} {6, 8, 4} {7, 7, 3, 8, 2} {7, 3, 8, 2, 2} {4, 2, 3, 1, 2, 5} {4, 5, 3, 4, 7, 5} {6, 0, -1, 3, 5, 0, -3} {6, 5, 9, 11, 6, 3, -3} Exercise : reverseLines Write a method called reverseLines that takes a Scanner containing an input file as a parameter and that echoes the input file to System.out with each line of text reversed. You should solve this problem in Practice-It! Exercise : append Write a method called append that accepts two integer arrays as parameters and that returns a new array that contains the result of appending the second array's values at the end of the first array. You should solve this problem in Practice-It! Exercise : Date subtractWeeks Write an instance method subtractWeeks that will be placed inside the Date class. The method accepts an integer parameter and shifts the date backward by that many weeks. (A week is exactly 7 days.) The date before 1/1 is 12/31. Here are some example calls on a given date object: Date d = new Date(9, 19); d.subtractWeeks(1); // d is now 9/12 d.subtractWeeks(2); // d is now 8/29 d.subtractWeeks(5); // d is now 7/25 d.subtractWeeks(20); // d is now 3/7 d.subtractWeeks(110); // d is now 1/26 (2 years prior) Test your solution to this problem in Practice-It. Exercise : Shark Shark objects should alternate between moving to the north and south as follows: first move 1 step north, then 2 steps south, then 3 steps north, then 4 steps south, then 5 steps north, then 6 steps south, and so on, each time moving one farther than previously. Solve this program in jGRASP with CritterMain, then test it using the Practice-it link above. Exercise : array simulation Consider the following method: public static void arrayMystery(String[] a) { for (int i = 0; i < a.length; i++) { a[i] += a[a.length - 1 - i]; } } In the left-hand column below are specific lists of strings. Indicate in the right-hand column what values would be stored in the list after method mystery executes if the string list in the left-hand column is passed to it as a parameter. {"a", "b", "c"} {"ac", "bb" ,"cac"} {"a", "bb", "c", "dd"} {"add", "bbc", "cbbc", "ddadd"} {"z", "y", "142", "w", "xx"} {"zxx", "yw", "142142", "wyw", "xxzxx"} If you finish them all... If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook. You can view an exercise, type a solution, and submit it to see if you have solved it correctly. Choose some problems from the book and try to solve them!