Java程序辅导

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

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
OOP Lab 3 Exercises: Instances, Arrays, and Encapsulation OOP Lab 3 Exercises: Instances, Arrays, and Encapsulation Authors: Joshua Ritterman Ewan Klein Version: 1.4 Date: 2009-01-29 Contents Preamble Exercises Exercise 1: Looking at the Weather Sample solution Exercise 2: The Video Store: changing things behind the scenes Sample solution Exercise 3: Adding Customers to the Video Store Sample solution Preamble Before doing the exercises, make sure you have read Chapter 3 & 4 of the textbook Head First Java. Exercises Exercise 1: Looking at the Weather I am trying to write a class WeeklyWeatherData to calculate some simple statistics for a week's weather. Here's my code for the launcher: /** * Test out the WeeklyWeatherClass * */ public class WeeklyWeatherDataLauncher { public static void main(String[] args) { double[] rain = { 5.34, 2.34, 0.0, 0.0, 3.23, 0.0, 2.42 }; double[] pressure = { 99.3, 95.34, 101.3, 98.42, 103.4, 100.0, 102.87 }; WeeklyWeatherData wd = new WeeklyWeatherData(); wd.setData(rain, pressure); wd.calculateStats(); // should be 5.35 System.out.println("Maximum Rainfall: " + wd.getMaxRain()); // should be ~ 1.904 System.out.println("Average Rainfall: " + wd.getAvgRain()); } } And here's my code so far for WeeklyWeatherData: public class WeeklyWeatherData { static int NUMDAYS = 7; double[] rainFall = new double[NUMDAYS]; double[] avgPressure = new double[NUMDAYS]; double avgRain; double maxRain; void setData(double[] rain, double[] pressure) { rainFall = rain; avgPressure = pressure; } void calculateStats() { maxRain = 0.0; double rainSum = 0.0; for (int i = 1; i < rainFall.length-1; i++) { if (rainFall[i] >= maxRain) maxRain = rainFall[i]; rainSum += rainFall[i]; } //TODO define value of avgRain } double getAvgRain() { return avgRain; } double getMaxRain() { return maxRain; } } This is the output I'm getting: Maximum Rainfall: 3.23 Average Rainfall: 0.0 But the correct values should be 5.34 and approximately 1.904! Please fix up WeeklyWeatherData to get the right results and submit it to assignment Lab 3.1: Looking at the Weather on Web-CAT. Sample solution WeeklyWeatherData.java: public class WeeklyWeatherData { static int NUMDAYS = 7; double[] rainFall = new double[NUMDAYS]; double[] avgPressure = new double[NUMDAYS]; double avgRain; double maxRain; void setData(double[] rain, double[] pressure) { rainFall = rain; avgPressure = pressure; } void calculateStats() { maxRain = 0.0; double rainSum = 0.0; for (int i = 0; i < rainFall.length; i++) { if (rainFall[i] >= maxRain) maxRain = rainFall[i]; rainSum += rainFall[i]; } avgRain = rainSum / NUMDAYS; } double getAvgRain() { return avgRain; } double getMaxRain() { return maxRain; } } Exercise 2: The Video Store: changing things behind the scenes In this exercise, we will try to model 'Video Rental Inventory System' that was included as an optional exercise in Lab 2. We will use it to illustrate some of the benefits of encapsulation. Here is the basic code for the VideoStore class. /** * VideoStore class. * * @author Joshua Ritterman * @version 1.0 */ public class VideoStore { Video[] catalogue = new Video[10]; int videoCount; public void addVideo(String title) { if (videoCount > 10) { System.out.println("Sorry, the shelves are full"); } else { catalogue[videoCount] = new Video(); catalogue[videoCount].setTitle(title); videoCount++; } } public void checkOutVideo(int video) { catalogue[video].checkOut(); } public void returnVideo(int video) { catalogue[video].returnToStore(); } public void rateVideo(int video, int rating) { catalogue[video].addRating(rating); } public double ratingForVideo(int video) { return catalogue[video].getRating(); } public int getVideoByTitle(String title) { for (int i = 0; i < videoCount; i++) { if (title.equals(catalogue[i].getTitle())) return i; } return 0; } public String getVideoByIndex(int index) { if (catalogue[index] == null){ return "Video #" + index + " not found."; } else { return catalogue[index].getTitle(); } } public void listInventory() { for (int i = 0; i < videoCount; i++) { System.out.println(i + ": " + catalogue[i].getTitle()); System.out.println("\tRating:" + ratingForVideo(i)); if (catalogue[i].isCheckedOut()) { System.out.println("\tChecked out: Yes"); } else { System.out.println(" Checked out: No"); } } } } This in turn makes use of the Video class. /** * Model of a Video for the VideoStore scenario * * @author Joshua Ritterman * @version 1.0 */ public class Video { private String title; private Boolean checkedOut = false; private double averageRating; private int ratingSum = 0; private int ratingCount = 0; /** * Sets the title. */ public void setTitle(String iTitle) { title = iTitle; } /** * Gets the title. */ public String getTitle() { return title; } /** * Adds a rating. * * @param rate * The user rating for this video. */ public void addRating(int rate) { /* TODO: modify this method so that the lowest and highest * ratings are ignored if there are at least four ratings. */ ratingSum = rate + ratingSum; ratingCount = ratingCount + 1; averageRating = ratingSum / ratingCount; } /** * Gets a rating. */ public double getRating() { return averageRating; } /** * Sets video checked out */ public void checkOut() { checkedOut = true; } /** * Sets video not checked out. */ public void returnToStore() { checkedOut = false; } /** * Gets checkedOut value */ public Boolean isCheckedOut() { return checkedOut; } } The functioning of these classes is illustrated by VideoStoreLauncher. /** * @author Ewan Klein * */ public class VideoStoreLauncher { /** * @param args */ public static void main(String[] args) { // Test a Video. Video vid1 = new Video(); vid1.setTitle("The Godfather"); vid1.addRating(3); vid1.addRating(2); vid1.addRating(5); vid1.getRating(); String s1 = String.format("%s: %s", vid1.getTitle(), vid1.getRating()); System.out.println(s1); vid1.checkOut(); getStatus(vid1); vid1.returnToStore(); getStatus(vid1); // Test a VideoStore. VideoStore vs = new VideoStore(); vs.addVideo("Battleship Potemkin"); vs.addVideo("The Godfather"); vs.addVideo("City of Angels"); // Add user ratings for 'Battleship Potemkin'. vs.rateVideo(0, 5); vs.rateVideo(0, 4); vs.rateVideo(0, 4); vs.rateVideo(0, 3); vs.rateVideo(0, 5); vs.rateVideo(0, 4); vs.rateVideo(0, 4); vs.rateVideo(0, 3); System.out.println(vs.getVideoByIndex(3)); vs.checkOutVideo(0); vs.checkOutVideo(2); System.out.println("Average Rating for video #0: " + vs.ratingForVideo(0)); vs.listInventory(); } public static void getStatus(Video v) { String title = v.getTitle(); if (v.isCheckedOut()) { String s = String.format("'%s' is checked out.", title); System.out.println(s); } else { String s = String.format("'%s' is on the shelves.", title); System.out.println(s); } } } This set of classes seems to be working quite well. But now, you decide that you need to implement a more sophisticated rating model. Thanks to encapsulation, all we have to change is the addRating() method in the Video class. The ratingForVideo() and listInventory() methods of VideoStore will not have to change, since all the implementation details of the rating system were encapsulated in the Video class. New feature to implement: Modify the definition of addRating() in the Video class in the following way. If the rating count is less than or equal to 4, then nothing is changed. If the rating count is higher than 4, then you are to find the highest rating and lowest rating and discard them (and their counts) when finding the average. You are not to throw away all counts with the Max and Min ratings, just one instance of them. For example, if there are several ratings with the same Max and Min, only 2 ratings are to be discarded. Example 1: ratings entered: 1, 2, 4, rating count = 3 avg = 2.33 Example 2: ratings entered: 5, 4, 1, 4, 5, 5, 3, 2 rating count = 6 (8 - 2) discarded Max = 5 discarded Min = 1 avg = 3.83 Example 3: ratings entered: 5, 5, 5, 5, 4, 4 rating count = 4 (6 - 2) discarded Max = 5 discarded Min = 4 avg = 4.75 Submit your revised version of Video.java and VideoStore.java to assignment Lab 3.2: The Video Store on Web-CAT. Sample solution Video.java: /** * Model of a Video for the VideoStore scenario * * @author Joshua Ritterman * @version 1.0 */ public class Video { private String title; private Boolean checkedOut = false; private double averageRating; private int ratingSum = 0; private int ratingCount = 0; private int ratingMax = 0; private int ratingMin = 0; /** * Sets the title. */ public void setTitle(String iTitle) { title = iTitle; } /** * Gets the title. */ public String getTitle() { return title; } /** * Adds a rating. * * @param rate * The user rating for this video. */ public void addRating(int rate) { int normalizedCount = 0; int normalizedSum = 0; /* * Modified so that the lowest and highest ratings are ignored if there * are at least four ratings. */ if (rate > ratingMax) ratingMax = rate; if (rate < ratingMin) ratingMin = rate; ratingSum = rate + ratingSum; ratingCount = ratingCount + 1; if (ratingCount > 4) { normalizedSum = ratingSum - (ratingMax + ratingMin); normalizedCount = ratingCount - 2; } else { normalizedSum = ratingSum; normalizedCount = ratingCount; } if (normalizedCount > 0) averageRating = normalizedSum / normalizedCount; else averageRating = 0.0; } /** * Get a rating. */ public double getRating() { return averageRating; } /** * Set video to be checked out */ public void checkOut() { checkedOut = true; } /** * Set video not checked out. */ public void returnToStore() { checkedOut = false; } /** * Get checkedOut value */ public Boolean isCheckedOut() { return checkedOut; } } Exercise 3: Adding Customers to the Video Store Now we are going to add some Customers to the Video Store. A Customer is modeled by a class that has a instance variable for the name, and an array for the history of movies that the customer has rented. Here is a proposal for the VideoCustomer class. /** * VideoCustomer model for the VideoStore scenario. * We keep a history of the Videos that the customer has rented. * * @author Joshua Ritterman * @version 1.0 */ public class VideoCustomer { private String name; private String[] history = new String[10]; private int historyCount; public void setName(String iName) { name = iName; } public String getName() { return name; } public void addHistory(String title) { if (historyCount > 10) { System.out.println("Sorry, the history buffer is full"); } else { history[historyCount] = title; historyCount++; } } public String[] getHistory() { return history; } } In this exercise, you should add a feature to the VideoStore so that the system can recommend another movie that a customer may like based on their rental history: this should be the highest-rated video that the customer has not yet rented out. Starting from the revised class, VideoStoreC, implement the suggestVideo() method and update the checkOutVideo() method so that the video in question is added to the customer's history. /** * VideoStore class. * * @author Joshua Ritterman * @version 1.0 */ public class VideoStoreC { Video[] catalogue = new Video[10]; VideoCustomer[] customers = new VideoCustomer[10]; int videoCount = 0; int customerCount = 0; public void enrolCustomer(String name) { customers[customerCount] = new VideoCustomer(); customers[customerCount++].setName(name); } public void addVideo(String title) { if (videoCount > 10) { System.out.println("Sorry, the shelves are full"); } else { catalogue[videoCount] = new Video(); catalogue[videoCount].setTitle(title); videoCount++; } } public void checkOutVideo(int video, String customer) { // TODO: Add this video to the customer's checkout history catalogue[video].checkOut(); } /** * @param customer The customer receiving a suggestion. * @return The index of video with above-threshold rating */ public int suggestVideo(String customer) { double likesThreshold = 3.0; int videoIndex = 0; // TODO: Suggest another video that is rated highly. return videoIndex; } void returnVideo(int video) { catalogue[video].returnToStore(); } void rateVideo(int video, int rating) { catalogue[video].addRating(rating); } double ratingForVideo(int video) { return catalogue[video].getRating(); } int getVideoByTitle(String title) { for (int i = 0; i < videoCount; i++) { if (title.equals(catalogue[i].getTitle())) return i; } return 0; } public void listInventory() { for (int i = 0; i < videoCount; i++) { System.out.println(i + ": " + catalogue[i].getTitle()); System.out.println("\tRating:" + ratingForVideo(i)); if (catalogue[i].isCheckedOut()) { System.out.println("\tChecked out: Yes"); } else { System.out.println(" Checked out: No"); } } } } Submit your revised version of VideoStoreC.java to assignment Lab 3.3: Adding Customers on Web-CAT. Sample solution VideoStoreC.java: /** * VideoStore class. * * @author Joshua Ritterman * @version 1.0 */ public class VideoStoreC { private Video[] catalogue = new Video[10]; private VideoCustomer[] customers = new VideoCustomer[10]; private int videoCount = 0; private int customerCount = 0; public void enrolCustomer(String name) { customers[customerCount++] = new VideoCustomer(); customers[customerCount].setName(name); } public void addVideo(String title) { if (videoCount > 10) { System.out.println("Sorry, the shelves are full"); } else { catalogue[videoCount] = new Video(); catalogue[videoCount].setTitle(title); videoCount++; } } public void checkOutVideo(int video, String customer) { catalogue[video].checkOut(); for (VideoCustomer c : customers) { if (customer.equals(c.getName())) { c.addHistory(catalogue[video].getTitle()); } } } /** * @param customer * The customer receiving a suggestion. * @return The index of video with above-threshold rating */ public int suggestVideo(String customer) { double likesThreshold = 3.0; int videoIndex = 0; boolean seen = false; for (VideoCustomer c : customers) { for (Video v : catalogue) { seen = false; for (String historyTitle : c.getHistory()) { if (historyTitle.equals(v.getTitle())) { seen = true; } } if (!seen && v.getRating() > likesThreshold) { return videoIndex; } videoIndex++; } } return videoIndex; } void returnVideo(int video) { catalogue[video].returnToStore(); } void rateVideo(int video, int rating) { catalogue[video].addRating(rating); } double ratingForVideo(int video) { return catalogue[video].getRating(); } int getVideoByTitle(String title) { for (int i = 0; i < videoCount; i++) { if (title.equals(catalogue[i].getTitle())) return i; } return 0; } public void listInventory() { for (int i = 0; i < videoCount; i++) { System.out.println(i + ": " + catalogue[i].getTitle()); System.out.println("\tRating:" + ratingForVideo(i)); if (catalogue[i].isCheckedOut()) { System.out.println("\tChecked out: Yes"); } else { System.out.println("\tChecked out: No"); } } } } footer This text is a component of the course Informatics 1: Object-Oriented Programming, University of Edinburgh. The HTML was generated with docutils. Date: Thu 29 Jan 2009 10:39:38 GMT OOP Informatics Home