├── README.md ├── Reference ├── exam2Reference.pdf ├── exam3Reference.pdf └── exam4Reference.pdf ├── UMLAnalysis ├── The Bright Fresh Milk System.docx ├── UML类图.jpg ├── UML类图.vsdx ├── 分析1.0.xlsx ├── 分析1.1.xlsx ├── 实验分析.docx └── 继承关系.xlsx ├── bigWork └── src │ ├── bigWork │ ├── ContactPerson.java │ ├── IndividualTourist.java │ ├── Person.java │ ├── Tourist.java │ ├── TouristGroup.java │ └── TouristInformationSystem.java │ └── file.txt ├── exam2.1 └── src │ ├── Product.java │ ├── ProductArray.java │ └── TestProductArray.java ├── exam2.2 └── src │ ├── Coffee.java │ ├── CoffeeShop.java │ ├── CoffeeShopApplication.java │ └── resources │ └── inherit.gif ├── exam2 └── src │ ├── BrightFreshMilkSystem.java │ ├── Catalog.java │ ├── CurrentOrder.java │ ├── Jelly.java │ ├── MilkDrink.java │ ├── OrderItem.java │ ├── Product.java │ ├── PureMilk.java │ ├── Sale.java │ └── Yogurt.java ├── exam3.0 └── src │ ├── Rectangle.java │ ├── Shape.java │ └── XMLElement.java ├── exam3.1 ├── classFile │ ├── Catalog.class │ ├── CurrentOrder.class │ ├── Jelly.class │ ├── MilkDrink.class │ ├── OrderItem.class │ ├── Product.class │ ├── PureMilk.class │ ├── Sale.class │ └── Yogurt.class └── src │ ├── BrightFreshMilk.java │ ├── HTMLSalesFormatter.java │ ├── PlainTextSalesFormatter.java │ ├── SalesFormatter.java │ └── XMLSalesFormatter.java ├── exam4.0 ├── catalog.dat ├── classFiles │ ├── Catalog.class │ ├── CurrentOrder.class │ ├── HTMLSalesFormatter.class │ ├── Jelly.class │ ├── MilkDrink.class │ ├── OrderItem.class │ ├── PlainTextSalesFormatter.class │ ├── Product.class │ ├── PureMilk.class │ ├── Sale.class │ ├── SalesFormatter.class │ ├── XMLSalesFormatter.class │ ├── XMLSalesFormatter.java │ └── Yogurt.class ├── empty.dat └── src │ ├── BrightFreshMilk.java │ ├── CatalogLoader.java │ ├── DataFormatException.java │ ├── FileCatalogLoader.java │ └── TestFileCatalogLoader.java └── exam4.1 ├── catalog.dat ├── classFiles ├── Catalog.class ├── CatalogLoader.class ├── CurrentOrder.class ├── DataField.class ├── DataFormatException.class ├── FileCatalogLoader.class ├── HTMLSalesFormatter.class ├── Jelly.class ├── MilkDrink.class ├── OrderItem.class ├── PlainTextSalesFormatter.class ├── Product.class ├── PureMilk.class ├── Sale.class ├── SalesFormatter.class ├── XMLSalesFormatter.class ├── XMLSalesFormatter.java └── Yogurt.class └── src └── BrightFreshMilkGUI.java /README.md: -------------------------------------------------------------------------------- 1 | # learning Java route 2 | * [use UML graph to descrip classes](./UMLAnalysis) 3 | * [code with OOP](./exam2.2) 4 | * [use list](./exam2/) 5 | * [Java Array](./exam2.1/) 6 | * [understand abstract calss and interface](./exam3.0) 7 | * [code with singleton Pattern](./exam3.1) 8 | * [deal with expection](./exam4.0/) 9 | * [GUI coding](./exam4.1/) 10 | # Reference Documents 11 | * [exam2.* refernce document](./Reference/exam2Reference.pdf) 12 | * [exam3.* refernce document](./Reference/exam3Reference.pdf) 13 | * [exam4.* refernce document](./Reference/exam4Reference.pdf) -------------------------------------------------------------------------------- /Reference/exam2Reference.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/Reference/exam2Reference.pdf -------------------------------------------------------------------------------- /Reference/exam3Reference.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/Reference/exam3Reference.pdf -------------------------------------------------------------------------------- /Reference/exam4Reference.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/Reference/exam4Reference.pdf -------------------------------------------------------------------------------- /UMLAnalysis/The Bright Fresh Milk System.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/UMLAnalysis/The Bright Fresh Milk System.docx -------------------------------------------------------------------------------- /UMLAnalysis/UML类图.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/UMLAnalysis/UML类图.jpg -------------------------------------------------------------------------------- /UMLAnalysis/UML类图.vsdx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/UMLAnalysis/UML类图.vsdx -------------------------------------------------------------------------------- /UMLAnalysis/分析1.0.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/UMLAnalysis/分析1.0.xlsx -------------------------------------------------------------------------------- /UMLAnalysis/分析1.1.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/UMLAnalysis/分析1.1.xlsx -------------------------------------------------------------------------------- /UMLAnalysis/实验分析.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/UMLAnalysis/实验分析.docx -------------------------------------------------------------------------------- /UMLAnalysis/继承关系.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/UMLAnalysis/继承关系.xlsx -------------------------------------------------------------------------------- /bigWork/src/bigWork/ContactPerson.java: -------------------------------------------------------------------------------- 1 | package bigWork; 2 | 3 | public class ContactPerson extends Person { 4 | private String jobPosition; 5 | 6 | /** 7 | * 8 | * @param initName 9 | * @param initTelephoneNumber 10 | * @param initEmail 11 | * @param initJobPosition 12 | */ 13 | public ContactPerson(String initName, long initTelephoneNumber, String initEmail, String initJobPosition) { 14 | super(initName, initTelephoneNumber, initEmail); 15 | this.jobPosition = initJobPosition; 16 | } 17 | 18 | /** 19 | * @return the jobPosition 20 | */ 21 | public String getJobPosition() { 22 | return jobPosition; 23 | } 24 | 25 | /** 26 | * @param jobPosition 27 | * the jobPosition to set 28 | */ 29 | public void setJobPosition(String jobPosition) { 30 | this.jobPosition = jobPosition; 31 | } 32 | 33 | /** 34 | * @return a string contain the information of ContactPerson 35 | */ 36 | public String toString() { 37 | String str; 38 | str = super.toString(); 39 | str = str + ", jobPosition:" + this.getJobPosition(); 40 | return str; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /bigWork/src/bigWork/IndividualTourist.java: -------------------------------------------------------------------------------- 1 | package bigWork; 2 | 3 | public class IndividualTourist implements Tourist { 4 | private String ID; 5 | private Person person; 6 | 7 | /** 8 | * 9 | * @param initID 10 | * @param initName 11 | * @param initTelephoneNumber 12 | * @param initEmail 13 | */ 14 | public IndividualTourist(String initID, String initName, long initTelephoneNumber, String initEmail) { 15 | this.ID = initID; 16 | person = new Person(initName, initTelephoneNumber, initEmail); 17 | } 18 | 19 | /** 20 | * @return ID 21 | */ 22 | public String getID() { 23 | return this.ID; 24 | } 25 | 26 | /** 27 | * @return a string of the IndividualTourist 28 | */ 29 | public String toString() { 30 | String str = new String(); 31 | str = str + "ID: " + getID() + ", " + person.toString(); 32 | return str; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /bigWork/src/bigWork/Person.java: -------------------------------------------------------------------------------- 1 | package bigWork; 2 | 3 | public class Person { 4 | private String name; 5 | private long telephoneNumber; 6 | private String email; 7 | 8 | /** 9 | * 10 | * @param initName 11 | * @param initTelephoneNumber 12 | * @param initEmail 13 | */ 14 | public Person(String initName, long initTelephoneNumber, String initEmail) { 15 | this.name = initName; 16 | this.telephoneNumber = initTelephoneNumber; 17 | this.email = initEmail; 18 | } 19 | 20 | /** 21 | * @return name 22 | */ 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | /** 28 | * @param name 29 | * the name to set 30 | */ 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | /** 36 | * @return the telephoneNumber 37 | */ 38 | public long getTelephoneNumber() { 39 | return telephoneNumber; 40 | } 41 | 42 | /** 43 | * @param telephoneNumber 44 | * the telephoneNumber to set 45 | */ 46 | public void setTelephoneNumber(int telephoneNumber) { 47 | this.telephoneNumber = telephoneNumber; 48 | } 49 | 50 | /** 51 | * @return the email 52 | */ 53 | public String getEmail() { 54 | return email; 55 | } 56 | 57 | /** 58 | * @param email 59 | * the email to set 60 | */ 61 | public void setEmail(String email) { 62 | this.email = email; 63 | } 64 | 65 | /** 66 | * @return a string contain all information of the person 67 | */ 68 | public String toString() { 69 | String str = new String(); 70 | str = str + "name: " + this.getName() + ", telephoneNumber: " + this.getTelephoneNumber() + ", email: " 71 | + this.getEmail(); 72 | return str; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /bigWork/src/bigWork/Tourist.java: -------------------------------------------------------------------------------- 1 | package bigWork; 2 | 3 | public interface Tourist { 4 | String getID(); 5 | String toString(); 6 | } 7 | -------------------------------------------------------------------------------- /bigWork/src/bigWork/TouristGroup.java: -------------------------------------------------------------------------------- 1 | package bigWork; 2 | 3 | import java.util.List; 4 | 5 | public class TouristGroup implements Tourist { 6 | private String ID; 7 | private List contactPersons; 8 | 9 | /** 10 | * @param iD 11 | * @param contactPersons 12 | */ 13 | public TouristGroup(String iD, List contactPersons) { 14 | ID = iD; 15 | this.contactPersons = contactPersons; 16 | } 17 | 18 | /** 19 | * @return the iD 20 | */ 21 | public String getID() { 22 | return ID; 23 | } 24 | 25 | /** 26 | * @param iD 27 | * the iD to set 28 | */ 29 | public void setID(String iD) { 30 | ID = iD; 31 | } 32 | 33 | /** 34 | * @return the contactPersons 35 | */ 36 | public List getContactPersons() { 37 | return contactPersons; 38 | } 39 | 40 | /** 41 | * @param contactPersons 42 | * the contactPersons to set 43 | */ 44 | public void setContactPersons(List contactPersons) { 45 | this.contactPersons = contactPersons; 46 | } 47 | 48 | /** 49 | * @return the string that contain all information of the TouristGroup the 50 | * ID and the contanctPersons 51 | */ 52 | public String toString() { 53 | String str = new String(); 54 | str = str + "ID: " + getID(); 55 | int number = 1; 56 | for (ContactPerson contact : contactPersons) { 57 | str = "contactPerson" + number + ": " + contact.toString() + "\n"; 58 | number++; 59 | } 60 | return str; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /bigWork/src/bigWork/TouristInformationSystem.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/bigWork/src/bigWork/TouristInformationSystem.java -------------------------------------------------------------------------------- /bigWork/src/file.txt: -------------------------------------------------------------------------------- 1 | IndividualTourist_A001_Derrick_13751524569_4154@gmail.com 2 | IndividualTourist_A002_Devin_13815328954_415vs4@gmail.com 3 | IndividualTourist_A003_Don_13645849875_415v17s4@qq.com 4 | TouristGroup_B001_Earl_13515864581_cxwwcex@qq.com_commander 5 | TouristGroup_B001_Ellis_15825621235_cxsxex@yahoo.com_guider 6 | TouristGroup_B002_Felix_13915152556_xwwcex@yahoo.com_commander 7 | TouristGroup_B002_Gilbert_13948425487_sxex@163.com_guider 8 | -------------------------------------------------------------------------------- /exam2.1/src/Product.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This class models an Product. The following information is maintained: 3 | *
    4 | *
  1. the ID of the Product, an int
  2. 5 | *
  3. the name of the Product, a String
  4. 6 | *
  5. the price of the Product, a double
  6. 7 | *
8 | * 9 | * @author Grover Zhu 10 | * @version 1.0.0 11 | */ 12 | public class Product { 13 | 14 | /* The ID of the Product */ 15 | private int id; 16 | 17 | /* The name of the Product */ 18 | private String name; 19 | 20 | /* The price of the Product */ 21 | private double price; 22 | 23 | /** 24 | * Creates an Product object with the specified ID, name and price. 25 | * 26 | * @param initialId the ID of the Product. 27 | * @param initialName the name of the Product. 28 | * @param initialprice the price of the Product. 29 | */ 30 | public Product(int initialId, String initialName, double initialPrice) { 31 | 32 | this.id = initialId; 33 | this.name = initialName; 34 | this.price = initialPrice; 35 | } 36 | 37 | /** 38 | * Returns the ID of this Product. 39 | * 40 | * @return the ID of this Product. 41 | */ 42 | public int getId() { 43 | 44 | return this.id; 45 | } 46 | 47 | /** 48 | * Returns the name of this Product. 49 | * 50 | * @return the name of this Product. 51 | */ 52 | public String getName() { 53 | 54 | return this.name; 55 | } 56 | 57 | /** 58 | * Returns the Price of this Product. 59 | * 60 | * @return the Price of this Product. 61 | */ 62 | public double getPrice() { 63 | 64 | return this.price; 65 | } 66 | 67 | /** 68 | * Modifies the Price of this Product. 69 | * 70 | * @param newPrice the new Price of this Product. 71 | */ 72 | public void setPrice(double newPrice) { 73 | 74 | this.price = newPrice; 75 | } 76 | 77 | /** 78 | * Returns the string representation of this Product in the following 79 | * format: Product[ID,name,Price] 80 | * 81 | * @return a string representation of this Product. 82 | */ 83 | public String toString() { 84 | 85 | return "Product[" + getId() + "," + getName() + "," + getPrice() +"]"; 86 | } 87 | } -------------------------------------------------------------------------------- /exam2.1/src/ProductArray.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This class contains methods to process arrays of {@link Product} objects. 3 | * 4 | * @author Grover Zhu 5 | * @version 1.0.0 6 | * @see Product 7 | */ 8 | public class ProductArray { 9 | 10 | /** 11 | * Creates an array with three objects of class {@link Product}. 12 | *

13 | * The first element of the array is the object 14 | * first, the second element of the array is 15 | * the object second, and the third element of the 16 | * array is the object third. 17 | *

18 | * 19 | * @param first a {@link Product} object. 20 | * @param second a {@link Product} object. 21 | * @param third a {@link Product} object. 22 | * @return an array with the objects first, 23 | * second, and third. 24 | */ 25 | public static Product[] makeArray(Product first, Product second, 26 | Product third) { 27 | 28 | Product[] product = new Product[3]; 29 | product[0] = first; 30 | product[1] = second; 31 | product[2] = third; 32 | return product; 33 | /* PLACE YOUR CODE HERE */ 34 | // return null; // REMOVE; USED SO THIS FILE COMPILES 35 | } 36 | 37 | /** 38 | * Creates a new array from the specified array of {@link Product} 39 | * objects. 40 | *

41 | * The elements in the new array have the same order as those in 42 | * the specified array. 43 | *

44 | * 45 | * @param array an array that contains objects of class {@link Product}. 46 | * @return a new array of the objects in the specified array. 47 | */ 48 | public static Product[] copyArray(Product[] array) { 49 | 50 | /* PLACE YOUR CODE HERE */ 51 | if (array == null){ 52 | return null; 53 | }else{ 54 | Product[] product = array.clone(); 55 | return product; 56 | } 57 | 58 | } 59 | 60 | 61 | /** 62 | * Returns the {@link Product} object with the specified ID. 63 | * 64 | * @param array an array that contains objects of class {@link Product}. 65 | * @param id an Product ID. 66 | * @return The {@link Product} object with the specifed 67 | * ID. Returns null if there are no Products 68 | * in the specified array with the specifed ID. 69 | */ 70 | public static Product getProduct(Product[] array, int id) { 71 | 72 | /* PLACE YOUR CODE HERE */ 73 | for (Product product : array){ 74 | if (product.getId() == id){ 75 | return product; 76 | } 77 | } 78 | return null; // REMOVE; USED SO THIS FILE COMPILES 79 | } 80 | 81 | /** 82 | * Returns the number of Products whose price is Lower than the specified 83 | * dollar amount. 84 | * 85 | * @param array an array that contains objects of class {@link Product}. 86 | * @param amount a dollar amount. 87 | * @return the number of Products whose price is Lower than the 88 | * specified dollar amount. 89 | */ 90 | public static int countLowerPrice(Product[] array, double amount) { 91 | 92 | /* PLACE YOUR CODE HERE */ 93 | int number = 0; 94 | for (Product product : array){ 95 | if (product.getPrice() < amount){ 96 | number++; 97 | } 98 | } 99 | return number; // REMOVE; USED SO THIS FILE COMPILES 100 | } 101 | 102 | /** 103 | * Returns the sum of the price of the Products in the specified 104 | * array. 105 | * 106 | * @param array an array that contains objects of class {@link Product}. 107 | * @return the sum of the price of the Products in the specified 108 | * array. 109 | */ 110 | // for-each loop 111 | public static double sumPrice(Product[] array) { 112 | 113 | /* PLACE YOUR CODE HERE */ 114 | double sum = 0; 115 | for (Product product : array){ 116 | sum = sum + product.getPrice(); 117 | } 118 | return sum; // REMOVE; USED SO THIS FILE COMPILES 119 | } 120 | 121 | /** 122 | * Obtains the Lowest price in the specified array. 123 | * 124 | * @param array an array that contains objects of class {@link Product}. 125 | * @return the Lowest price in the specified array. 126 | */ 127 | 128 | // for-each loop 129 | public static double getLowestPrice(Product[] array) { 130 | 131 | /* PLACE YOUR CODE HERE */ 132 | double price = array[0].getPrice(); 133 | for (Product product : array){ 134 | if (product.getPrice() < price){ 135 | price = product.getPrice(); 136 | } 137 | } 138 | return price; // REMOVE; USED SO THIS FILE COMPILES 139 | } 140 | 141 | /** 142 | * Increases the Price of every Product in the specified array by the 143 | * specified amount. 144 | * 145 | * @param array an array that contains objects of class {@link Product}. 146 | */ 147 | // for-each loop 148 | public static void increaseAll(Product[] array, double amount) { 149 | 150 | /* PLACE YOUR CODE HERE */ 151 | for (Product product : array){ 152 | product.setPrice(product.getPrice() + amount); 153 | } 154 | 155 | } 156 | 157 | /** 158 | * Returns a string representation of the specified 159 | * {@link Product} array. 160 | *

161 | * Uses the method toString in class Product 162 | * to obtain the string representation of each object in the array. 163 | *

164 | * A new line character ( \n ) separates the string representations 165 | * of each Product object. For example: 166 | *

167 | *
168 | 	 * Product[102,cruise,68250.0]\n
169 | 	 * Product[101,domestic,36000.0]\n
170 | 	 * Product[103,outbound,92175.0]
171 | 	 * 
172 | *

173 | * Note that the string returned does not end with a new line 174 | * character (\n). 175 | *

176 | *

177 | * This method assumes that every element in the specified array 178 | * contains a valid reference to an Product object. 179 | *

180 | * 181 | * @param array an array that contains objects of class {@link Product}. 182 | * @return the string representation of the specified array 183 | */ 184 | public static String displayAll(Product[] array) { 185 | 186 | /* PLACE YOUR CODE HERE */ 187 | String str = new String(); 188 | if (array.length == 0) { 189 | return ""; 190 | } else { 191 | int length = array.length; 192 | for (int i = 0; i < length - 1; i++) { 193 | str = str + "Product[" + array[i].getId() + "," + array[i].getName() + "," + array[i].getPrice() + "]\n"; 194 | } 195 | str = str + "Product[" + array[length - 1].getId() + "," + array[length - 1].getName() + "," + array[length - 1].getPrice() + "]"; 196 | return str; // REMOVE; USED SO THIS FILE COMPILES 197 | } 198 | } 199 | } -------------------------------------------------------------------------------- /exam2.1/src/TestProductArray.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | /** 4 | * Tests the class ProductArray 5 | * 6 | * @author Grover Zhu 7 | * @version 1.0.0 8 | * @see productArray 9 | * @see Product 10 | */ 11 | public class TestProductArray { 12 | 13 | /* Standard output stream */ 14 | private static PrintWriter stdOut = new PrintWriter(System.out, true); 15 | 16 | /* Standard error stream */ 17 | private static PrintWriter stdErr = new PrintWriter(System.err, true); 18 | 19 | /* Variables that contains the test objects */ 20 | private Product first; 21 | private Product second; 22 | private Product third; 23 | private Product fourth; 24 | private Product[] empty; 25 | private Product[] array; 26 | private int nonProductId; 27 | 28 | /** 29 | * Tests methods of class {@link ProductArray} 30 | * 31 | * @param args 32 | * not used 33 | */ 34 | public static void main(String args[]) { 35 | 36 | stdOut.println(""); 37 | stdOut.println("Testing class ProductArray..."); 38 | 39 | TestProductArray tester = new TestProductArray(); 40 | if (tester.testMakeArray() & tester.testCopyArray() & tester.testGetProduct() & tester.testCountLowerPrice() 41 | & tester.testSumPrice() & tester.testGetLowestPrice() & tester.testIncreaseAll() 42 | & tester.testDisplayAll()) { 43 | stdOut.println("All tests passed"); 44 | } 45 | } 46 | 47 | 48 | /** 49 | * Displays a message in the standard error stream if the value specified by 50 | * parameter condition is false. 51 | * 52 | * @param message 53 | * the error message. 54 | * @param condition 55 | * the test condition. 56 | * @return the value of condition 57 | */ 58 | public static boolean assertTrue(String message, boolean condition) { 59 | 60 | if (!condition) { 61 | stdErr.print("** Test failure "); 62 | stdErr.println(message); 63 | 64 | return false; 65 | } else { 66 | 67 | return true; 68 | } 69 | 70 | } 71 | 72 | /** Assign the initial value to the test variables */ 73 | private void setUp() { 74 | 75 | first = new Product(101, "First", 1000.0); 76 | second = new Product(102, "Second", 100.0); 77 | third = new Product(103, "Third", 1000.0); 78 | fourth = new Product(104, "Fourth", 500.0); 79 | 80 | nonProductId = 106; 81 | 82 | empty = new Product[0]; 83 | 84 | array = new Product[4]; 85 | array[0] = first; 86 | array[1] = second; 87 | array[2] = third; 88 | array[3] = fourth; 89 | } 90 | 91 | /** 92 | * Tests the method makeArray. 93 | * 94 | * @return true if all test passed; otherwise returns 95 | * false. 96 | */ 97 | public boolean testMakeArray() { 98 | 99 | setUp(); 100 | 101 | boolean test = true; 102 | 103 | Product[] result = ProductArray.makeArray(first, second, third); 104 | 105 | test = test && assertTrue("1, testing method makeArray", result instanceof Product[]); 106 | test = test && assertTrue("2, testing method makeArray", result.length == 3); 107 | test = test && assertTrue("3, testing method makeArray", result[0].equals(first)); 108 | test = test && assertTrue("4, testing method makeArray", result[1].equals(second)); 109 | test = test && assertTrue("5, testing method makeArray", result[2].equals(third)); 110 | 111 | return test; 112 | } 113 | 114 | /** 115 | * Tests the method copyArray. 116 | * 117 | * @return true if all test passed; otherwise returns 118 | * false. 119 | */ 120 | public boolean testCopyArray() { 121 | 122 | setUp(); 123 | 124 | boolean test = true; 125 | 126 | Product[] resultEmpty = ProductArray.copyArray(empty); 127 | 128 | test = test && assertTrue("1, testing method copyArray", resultEmpty instanceof Product[]); 129 | test = test && assertTrue("2, testing method copyArray", resultEmpty.length == 0); 130 | 131 | Product resultArray[] = ProductArray.copyArray(array); 132 | 133 | test = test && assertTrue("3, testing method copyArray", resultArray instanceof Product[]); 134 | test = test && assertTrue("4, testing method copyArray", resultArray.length == 4); 135 | test = test && assertTrue("5, testing method copyArray", resultArray[0] == first); 136 | test = test && assertTrue("6, testing method copyArray", resultArray[1] == second); 137 | test = test && assertTrue("7, testing method copyArray", resultArray[2] == third); 138 | test = test && assertTrue("8, testing method copyArray", resultArray[3] == fourth); 139 | 140 | return test; 141 | } 142 | 143 | /** 144 | * Tests the method getProduct. 145 | * 146 | * @return true if all test passed; otherwise returns 147 | * false. 148 | */ 149 | public boolean testGetProduct() { 150 | 151 | setUp(); 152 | 153 | boolean test = true; 154 | 155 | test = test && assertTrue("1, testing method getProduct", ProductArray.getProduct(empty, nonProductId) == null); 156 | 157 | Product product; 158 | 159 | product = ProductArray.getProduct(array, first.getId()); 160 | test = test && assertTrue("2, testing method getProduct", product != null && product.equals(first)); 161 | product = ProductArray.getProduct(array, second.getId()); 162 | test = test && assertTrue("3, testing method getProduct", product != null && product.equals(second)); 163 | product = ProductArray.getProduct(array, third.getId()); 164 | test = test && assertTrue("4, testing method getProduct", product != null && product.equals(third)); 165 | product = ProductArray.getProduct(array, fourth.getId()); 166 | test = test && assertTrue("5, testing method getProduct", product != null && product.equals(fourth)); 167 | test = test && assertTrue("6, testing method getProduct", ProductArray.getProduct(array, nonProductId) == null); 168 | 169 | return test; 170 | } 171 | 172 | /** 173 | * Tests the method countLowerPrice. 174 | * 175 | * @return true if all test passed; otherwise returns 176 | * false. 177 | */ 178 | public boolean testCountLowerPrice() { 179 | 180 | setUp(); 181 | 182 | boolean test = true; 183 | 184 | test = test && assertTrue("1, testing method countLowerPrice", ProductArray.countLowerPrice(empty, 0.0) == 0); 185 | 186 | test = test && assertTrue("2, testing method countLowerPrice", ProductArray.countLowerPrice(array, 0.0) == 0); 187 | test = test 188 | && assertTrue("3, testing method countLowerPrice", ProductArray.countLowerPrice(array, 200.0) == 1); 189 | test = test && assertTrue("4, testing method countLowerPrice", 190 | ProductArray.countLowerPrice(array, 100000.0) == 4); 191 | 192 | return test; 193 | } 194 | 195 | /** 196 | * Tests the method sumPrice 197 | * 198 | * @return true if all test passed; otherwise returns 199 | * false. 200 | */ 201 | public boolean testSumPrice() { 202 | 203 | setUp(); 204 | 205 | boolean test = true; 206 | 207 | test = test && assertTrue("1, testing method sumPrice", ProductArray.sumPrice(empty) == 0.0); 208 | 209 | test = test && assertTrue("2, testing method sumPrice", ProductArray.sumPrice(array) == first.getPrice() 210 | + second.getPrice() + third.getPrice() + fourth.getPrice()); 211 | 212 | return test; 213 | } 214 | 215 | /** 216 | * Tests the method getLowestPrice 217 | * 218 | * @return true if test passed; otherwise returns 219 | * false. 220 | */ 221 | public boolean testGetLowestPrice() { 222 | 223 | setUp(); 224 | 225 | boolean test = true; 226 | 227 | test = test && assertTrue("1, testing method getLowestPrice", ProductArray.getLowestPrice(array) == 100); 228 | 229 | Product[] arrayTwo = new Product[5]; 230 | arrayTwo[0] = new Product(101, "First", 2000.0); 231 | arrayTwo[1] = new Product(102, "Second", 100.0); 232 | arrayTwo[2] = new Product(103, "Third", 1000.0); 233 | arrayTwo[3] = new Product(104, "Fourth", 500.0); 234 | arrayTwo[4] = new Product(105, "Fifth", 500.0); 235 | 236 | test = test && assertTrue("2, testing method getLowestPrice", ProductArray.getLowestPrice(arrayTwo) == 100); 237 | 238 | return test; 239 | } 240 | 241 | /** 242 | * Tests the method increaseAll. 243 | * 244 | * @return true if all test passed; otherwise returns 245 | * false. 246 | */ 247 | public boolean testIncreaseAll() { 248 | 249 | setUp(); 250 | 251 | boolean test = true; 252 | 253 | double amount = 100.0; 254 | double salaryFirst = first.getPrice(); 255 | double salarySecond = second.getPrice(); 256 | double salaryThird = third.getPrice(); 257 | double salaryFourth = fourth.getPrice(); 258 | 259 | ProductArray.increaseAll(array, amount); 260 | test = test && assertTrue("1, testing method increaseAll", first.getPrice() == salaryFirst + amount); 261 | test = test && assertTrue("2, testing method increaseAll", second.getPrice() == salarySecond + amount); 262 | test = test && assertTrue("3, testing method increaseAll", third.getPrice() == salaryThird + amount); 263 | test = test && assertTrue("4, testing method increaseAll", fourth.getPrice() == salaryFourth + amount); 264 | 265 | return test; 266 | } 267 | 268 | /** 269 | * Tests the method displayAll. 270 | * 271 | * @return true if all test passed; otherwise returns 272 | * false. 273 | */ 274 | public boolean testDisplayAll() { 275 | 276 | setUp(); 277 | 278 | boolean test = true; 279 | 280 | test = test && assertTrue("1, testing method displayAll", ProductArray.displayAll(empty).equals("")); 281 | 282 | String result = ProductArray.displayAll(array); 283 | test = test && assertTrue("2, testing method displayAll", ProductArray.displayAll(array).equals( 284 | first.toString() + "\n" + second.toString() + "\n" + third.toString() + "\n" + fourth.toString())); 285 | 286 | return test; 287 | } 288 | } -------------------------------------------------------------------------------- /exam2.2/src/Coffee.java: -------------------------------------------------------------------------------- 1 | 2 | public class Coffee { 3 | private int id; 4 | private String name; 5 | private String taste; 6 | private double cost; 7 | /** 8 | * 9 | * @param initialId 10 | * @param initialName 11 | * @param initialTaste 12 | * @param initialcost 13 | */ 14 | public Coffee(int initialId, String initialName, String initialTaste, double initialcost) { 15 | this.id = initialId; 16 | this.name = initialName; 17 | this.taste = initialTaste; 18 | this.cost = initialcost; 19 | } 20 | /** 21 | * 22 | * @return name 23 | */ 24 | public String getName() { 25 | return this.name; 26 | } 27 | /** 28 | * 29 | * @return taste 30 | */ 31 | public String getTaste() { 32 | return this.taste; 33 | } 34 | /** 35 | * 36 | * @return id 37 | */ 38 | public int getId() { 39 | return this.id; 40 | } 41 | /** 42 | * 43 | * @return cost 44 | */ 45 | public double getCost() { 46 | return this.cost; 47 | } 48 | 49 | public String toString() { 50 | return "Coffee id: " + this.id + "\ttaste: " + this.taste + "\tname: " + this.name + "\tcost: " + this.cost 51 | + "\r\n"; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /exam2.2/src/CoffeeShop.java: -------------------------------------------------------------------------------- 1 | import java.io.PrintStream; 2 | import java.util.Collection; 3 | import java.util.Iterator; 4 | import java.util.Vector; 5 | 6 | public class CoffeeShop { 7 | 8 | private Collection cart; 9 | 10 | public CoffeeShop() { 11 | this.cart = new Vector(); 12 | } 13 | 14 | public String toString() { 15 | if (this.cart.size() == 0) 16 | return "empty"; 17 | Iterator iterator = this.cart.iterator(); 18 | StringBuffer stringbuffer = new StringBuffer(iterator.next().toString()); 19 | for (; iterator.hasNext(); stringbuffer.append(iterator.next() 20 | .toString())) { 21 | stringbuffer.append("\n"); 22 | } 23 | return stringbuffer.toString(); 24 | } 25 | /** 26 | * 27 | * @return total cost 28 | */ 29 | public double getTotalCost() { 30 | double d = 0.0D; 31 | if (this.cart.size() == 0) { 32 | System.err.println("There is no coffee in the cart!"); 33 | return 0.0D; 34 | } 35 | for (Iterator iterator = this.cart.iterator(); iterator.hasNext();) { 36 | d += ((Coffee) iterator.next()).getCost(); 37 | } 38 | return d; 39 | } 40 | /** 41 | * 42 | * @param coffee 43 | */ 44 | public void addCoffee(Coffee coffee) { 45 | if (coffee == null) { 46 | return; 47 | } else { 48 | this.cart.add(coffee); 49 | System.out.println("Add successfully"); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /exam2.2/src/CoffeeShopApplication.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.util.regex.Pattern; 4 | 5 | public class CoffeeShopApplication{ 6 | 7 | private static BufferedReader stdIn = 8 | new BufferedReader(new InputStreamReader(System.in)); 9 | private static PrintWriter stdOut = 10 | new PrintWriter(System.out, true); 11 | private static PrintWriter stdErr = 12 | new PrintWriter(System.err, true); 13 | 14 | private CoffeeShop coffeeShop; 15 | 16 | private static final int MIN_NUMBER = 0; 17 | 18 | private static final int MAX_NUMBER = 50; 19 | 20 | private static final double MIN_COST = 2.0; 21 | 22 | private static final double MAX_COST = 50.0; 23 | 24 | public static void main(String[] args) throws IOException, InterruptedException { 25 | 26 | CoffeeShopApplication application = new CoffeeShopApplication(); 27 | 28 | application.run(); 29 | } 30 | 31 | private void run() throws IOException, InterruptedException { 32 | 33 | coffeeShop = new CoffeeShop(); 34 | 35 | int choice = getChoice(); 36 | 37 | while (choice != 0) { 38 | 39 | if (choice == 1) { 40 | coffeeShop.addCoffee(readCoffee()); 41 | } else if (choice == 2) { 42 | stdOut.println(coffeeShop.toString()); 43 | } else if (choice == 3) { 44 | stdOut.println("Total Cost: " + coffeeShop.getTotalCost()); 45 | } 46 | Thread.sleep(1); 47 | choice = getChoice(); 48 | } 49 | } 50 | 51 | private int getChoice() throws IOException { 52 | 53 | /* PLACE YOUR CODE HERE */ 54 | int input; 55 | do { 56 | try { 57 | stdErr.println(); 58 | stdErr.print("[0] Quit\n" 59 | + "[1] Add Coffee\n" 60 | + "[2] Didsplay coffee Shop\n" 61 | + "[3] Display Total Cost\n" 62 | + "choice> "); 63 | stdErr.flush(); 64 | 65 | input = Integer.parseInt(stdIn.readLine()); 66 | 67 | stdErr.println(); 68 | 69 | if (0 <= input && input <= 3) { 70 | break; 71 | } else { 72 | stdErr.println("Invalid choice: " + input); 73 | } 74 | } catch (NumberFormatException nfe) { 75 | stdErr.println(nfe); 76 | } 77 | } while (true); 78 | 79 | return input; //you need to change it. 80 | } 81 | 82 | private Coffee readCoffee() throws IOException{ 83 | /* PLACE YOUR CODE HERE */ 84 | do{ 85 | stdErr.print("Input string >"); 86 | stdErr.flush(); 87 | String str = stdIn.readLine(); 88 | StringTokenizer stringTokenizer = new StringTokenizer(str, "_"); 89 | int number = stringTokenizer.countTokens(); 90 | if (number != 4) { 91 | System.out.println("Too much or too few values!"); 92 | continue; 93 | } else { 94 | try { 95 | int id = Integer.parseInt(stringTokenizer.nextToken()); 96 | String name = stringTokenizer.nextToken(); 97 | String tast = stringTokenizer.nextToken(); 98 | double cost = Double.parseDouble(stringTokenizer.nextToken()); 99 | if (id <= 0 || cost <= 0) { 100 | System.out.println("The number can't be negative"); 101 | continue; 102 | } else { 103 | Coffee coffee = new Coffee(id, name, tast, cost); 104 | return coffee; 105 | } 106 | } catch (NumberFormatException nfe) { 107 | stdErr.println(nfe); 108 | continue; 109 | } 110 | } 111 | }while(true); 112 | } 113 | 114 | 115 | } -------------------------------------------------------------------------------- /exam2.2/src/resources/inherit.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam2.2/src/resources/inherit.gif -------------------------------------------------------------------------------- /exam2/src/BrightFreshMilkSystem.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | import java.io.PrintWriter; 5 | import java.math.BigDecimal; 6 | import java.util.ArrayList; 7 | import java.util.Date; 8 | import java.util.List; 9 | 10 | 11 | /** 12 | * This class implements a Bright Fresh Milk System. 13 | * 14 | * @author author name 15 | * @version 1.0 16 | */ 17 | public class BrightFreshMilkSystem { 18 | 19 | private static BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); 20 | private static PrintWriter stdOut = new PrintWriter(System.out, true); 21 | private static PrintWriter stdErr = new PrintWriter(System.err, true); 22 | 23 | private Catalog catalog; 24 | private Sale sale; 25 | private CurrentOrder currentOrder; 26 | 27 | /** 28 | * Loads data and starts the application. 29 | * 30 | * @param args 31 | * String arguments. Not used. 32 | * @throws IOException 33 | * if there are errors in the input. 34 | * @throws InterruptedException 35 | */ 36 | public static void main(String[] args) throws IOException, InterruptedException { 37 | 38 | BrightFreshMilkSystem application = new BrightFreshMilkSystem(); 39 | application.run(); 40 | 41 | } 42 | 43 | /** 44 | * 45 | * @param initial 46 | */ 47 | private BrightFreshMilkSystem() { 48 | 49 | this.catalog = loadCatalog(); 50 | this.sale = loadSale(); 51 | this.currentOrder = loadCurrentOrder(); 52 | } 53 | 54 | /** 55 | * Initializes the Catalog object. 56 | */ 57 | private Catalog loadCatalog() { 58 | 59 | Catalog catalog = new Catalog(); 60 | List productList = new ArrayList(); 61 | 62 | productList.add(new PureMilk("A001", "milk,400ml", new BigDecimal("10"), new Date(), "25 days", "China", "3.5%", 63 | "2.9%")); 64 | productList.add(new PureMilk("A002", "skim milk,800ml", new BigDecimal("18"), new Date(), "30 days", "China", 65 | "3.1%", "3.9%")); 66 | 67 | productList.add(new Jelly("B001", "solid,250ml", new BigDecimal("8.5"), new Date(), "15 days", "solid", "80%")); 68 | productList.add(new Jelly("B002", "solid,400ml", new BigDecimal("14"), new Date(), "16 days", "solid", "85%")); 69 | 70 | productList.add( 71 | new Yogurt("C001", "chocolate flavor,270ml", new BigDecimal("5"), new Date(), "40 days", "chocolate")); 72 | productList.add(new Yogurt("C002", "strawberry flavor,400ml", new BigDecimal("10"), new Date(), "40 days", 73 | "strawberry")); 74 | 75 | productList.add(new MilkDrink("D001", "taro flavor,250ml", new BigDecimal("13.1"), new Date(), "25 days", 76 | "taro", "2.9%")); 77 | productList.add(new MilkDrink("D002", "apple flavor,400ml", new BigDecimal("16"), new Date(), "30 days", 78 | "apple", "3.8%")); 79 | 80 | catalog.setProductList(productList); 81 | return catalog; 82 | } 83 | 84 | /** 85 | * Initializes the Sale object. 86 | */ 87 | private Sale loadSale() { 88 | Sale sale = new Sale(); 89 | List orderList = new ArrayList(); 90 | sale.setOrderList(orderList); 91 | return sale; 92 | } 93 | 94 | /** 95 | * Initializes the CurrentOrder object. 96 | */ 97 | private CurrentOrder loadCurrentOrder() { 98 | CurrentOrder currentOrder = new CurrentOrder(); 99 | List orderItemList = new ArrayList(); 100 | 101 | PureMilk pureMilk = new PureMilk("A002", "skim milk,800ml", new BigDecimal("18"), new Date(), "30 days", 102 | "China", "3.1%", "3.9%"); 103 | orderItemList.add(new OrderItem(pureMilk, 2)); 104 | 105 | Yogurt yogurt = new Yogurt("C001", "chocolate flavor,270ml", new BigDecimal("5"), new Date(), "40 days", 106 | "chocolate"); 107 | orderItemList.add(new OrderItem(yogurt, 3)); 108 | 109 | MilkDrink milkDrink = new MilkDrink("D001", "taro flavor,250ml", new BigDecimal("13.1"), new Date(), "25 days", 110 | "taro", "2.9%"); 111 | orderItemList.add(new OrderItem(milkDrink, 1)); 112 | 113 | Jelly jelly = new Jelly("B001", "solid,250ml", new BigDecimal("8.5"), new Date(), "15 days", "solid", "80%"); 114 | orderItemList.add(new OrderItem(jelly, 3)); 115 | 116 | currentOrder.setOrderItemList(orderItemList); 117 | currentOrder.setOrderTotal(new BigDecimal("89.6")); 118 | return currentOrder; 119 | } 120 | 121 | /* 122 | * Presents the user with a menu of options and executes the selected task. 123 | */ 124 | private void run() throws IOException, InterruptedException { 125 | 126 | int choice = getChoice(); 127 | 128 | while (choice != 0) { 129 | if (choice == 1) { 130 | displayCatalog(); 131 | } else if (choice == 2) { 132 | displayProductInformationByCode(); 133 | } else if (choice == 3) { 134 | displayCurrentOrder(); 135 | } else if (choice == 4) { 136 | addProductToCurrentOrder(); 137 | } else if (choice == 5) { 138 | removeProductFromCurrentOrder(); 139 | } else if (choice == 6) { 140 | addCurrentOrderToSaleAndEmptyCurrentOrder(); 141 | } else if (choice == 7) { 142 | displaySale(); 143 | } 144 | Thread.sleep(1); 145 | choice = getChoice(); 146 | } 147 | } 148 | 149 | /* 150 | * Displays a menu of options and verifies the user's choice. 151 | * 152 | * @return an integer in the range [0,7] 153 | */ 154 | private int getChoice() throws IOException { 155 | 156 | int input; 157 | do { 158 | try { 159 | stdErr.println(); 160 | stdErr.print("[0] Quit\n" + "[1] Display the catalog\n" 161 | + "[2] Display the information of a product by its code\n" + "[3] Display the current order\n" 162 | + "[4] Add a product to the current order\n" + "[5] Remove a product from the current order\n" 163 | + "[6] Adds the current order to the store's sales and empties the current order\n" 164 | + "[7] Display the sales including all the orders that have been sold\n" + "choice> "); 165 | stdErr.flush(); 166 | 167 | input = Integer.parseInt(stdIn.readLine()); 168 | 169 | stdErr.println(); 170 | 171 | if (0 <= input && input <= 7) { 172 | break; 173 | } else { 174 | stdErr.println("Invalid choice: " + input); 175 | } 176 | } catch (NumberFormatException nfe) { 177 | stdErr.println(nfe); 178 | } 179 | } while (true); 180 | 181 | return input; 182 | } 183 | 184 | /* 185 | * Prompts user for a product code and locates the associated 186 | * Product object. 187 | * 188 | * @return reference to the Product object with the specified 189 | * code 190 | */ 191 | private Product readProduct() throws IOException { 192 | 193 | stdErr.print("Product code> "); 194 | stdErr.flush(); 195 | 196 | Product product = this.catalog.findProductByCode(stdIn.readLine()); 197 | if (product != null) { 198 | return product; 199 | } else { 200 | stdErr.println("There are no products with that code"); 201 | return null; 202 | } 203 | } 204 | 205 | /** 206 | * Displays the catalog. 207 | */ 208 | public void displayCatalog() { 209 | 210 | int size = this.catalog.getProductList().size(); 211 | 212 | if (size == 0) { 213 | stdErr.println("The catalog is empty"); 214 | } else { 215 | for (Product product : this.catalog.getProductList()) { 216 | stdOut.println(product.toString()); 217 | stdOut.flush(); 218 | } 219 | } 220 | } 221 | 222 | /** 223 | * Displays the information of a product 224 | */ 225 | public void displayProductInformationByCode() throws IOException { 226 | 227 | Product product = readProduct(); 228 | 229 | while (product == null) 230 | product = readProduct(); 231 | 232 | if (product instanceof Jelly) { 233 | Jelly jelly = (Jelly) product; 234 | System.out.println(jelly.toString()); 235 | } else if (product instanceof MilkDrink) { 236 | MilkDrink milkDrink = (MilkDrink) product; 237 | System.out.println(milkDrink.toString()); 238 | } else if (product instanceof PureMilk) { 239 | PureMilk pureMilk = (PureMilk) product; 240 | System.out.println(pureMilk.toString()); 241 | } else if (product instanceof Yogurt) { 242 | Yogurt yogurt = (Yogurt) product; 243 | System.out.println(yogurt.toString()); 244 | } else { 245 | System.out.println(product.toString()); 246 | } 247 | } 248 | 249 | /** 250 | * Displays the information of a Current Order 251 | */ 252 | public void displayCurrentOrder() throws IOException { 253 | if (currentOrder.getOrderItemList().size() == 0){ 254 | System.out.println("The current order is empty!"); 255 | }else{ 256 | System.out.println(currentOrder.toString()); 257 | } 258 | } 259 | 260 | /** 261 | * Add a product to the current order —if the specified product is already 262 | * part of the order, this command will modify the quantity of that product 263 | */ 264 | public void addProductToCurrentOrder() throws IOException { 265 | Product product = readProduct(); 266 | 267 | while (product == null) 268 | product = readProduct(); 269 | currentOrder.setOrderTotal(currentOrder.getOrderTotal().add(product.getPrice())); 270 | 271 | // if the specified product is already part of the order, modify the 272 | // quantity 273 | for (int i = 0; i < currentOrder.getOrderItemList().size(); i++) { 274 | OrderItem orderItem = currentOrder.getOrderItemList().get(i); 275 | if (product.getCode().equals(orderItem.getProduct().getCode())) { 276 | orderItem.setQuantity(orderItem.getQuantity() + 1); 277 | stdErr.println("Add successfully!"); 278 | return; 279 | } 280 | } 281 | 282 | // Add the product,if the specified product is not part of the order 283 | OrderItem newOrderItem = new OrderItem(product, 1); 284 | List orderItems = currentOrder.getOrderItemList(); 285 | orderItems.add(newOrderItem); 286 | currentOrder.setOrderItemList(orderItems); 287 | stdErr.println("Add successfully!"); 288 | 289 | } 290 | 291 | /** 292 | * Remove a product from the current order 293 | */ 294 | public void removeProductFromCurrentOrder() throws IOException { 295 | Product product = readProduct(); 296 | 297 | while (product == null) 298 | product = readProduct(); 299 | 300 | // find and remove 301 | for (int i = 0; i < currentOrder.getOrderItemList().size(); i++) { 302 | OrderItem orderItem = currentOrder.getOrderItemList().get(i); 303 | if (product.getCode().equals(orderItem.getProduct().getCode())) { 304 | currentOrder.getOrderItemList().remove(i); 305 | 306 | // subtract the money of the specified product 307 | BigDecimal money = orderItem.getProduct().getPrice().multiply(new BigDecimal(orderItem.getQuantity())); 308 | currentOrder.setOrderTotal(currentOrder.getOrderTotal().subtract(money)); 309 | 310 | stdErr.println("Remove successfully!"); 311 | } 312 | } 313 | } 314 | 315 | /** 316 | * Adds the current order to the store's sales and empties the current order 317 | */ 318 | public void addCurrentOrderToSaleAndEmptyCurrentOrder() throws IOException { 319 | 320 | sale.getOrderList().add(new CurrentOrder(currentOrder)); 321 | currentOrder.setOrderTotal(null); 322 | int length = currentOrder.getOrderItemList().size(); 323 | for (int index = length - 1; index > -1; index--){ 324 | currentOrder.getOrderItemList().remove(index); 325 | } 326 | currentOrder = new CurrentOrder(); 327 | System.out.println("Adds the current order to the sales and empties the " 328 | + "current order successfully!"); 329 | 330 | 331 | } 332 | 333 | /** 334 | * Display the sales including all the orders that have been sold. 335 | */ 336 | public void displaySale() throws IOException { 337 | List list = sale.getOrderList(); 338 | for (CurrentOrder order : list){ 339 | System.out.println(order.toString()); 340 | } 341 | 342 | } 343 | 344 | } -------------------------------------------------------------------------------- /exam2/src/Catalog.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | /** 4 | * 5 | */ 6 | 7 | /** 8 | * @author Administrator 9 | * 10 | */ 11 | public class Catalog { 12 | private List productList; 13 | 14 | public Catalog(){ 15 | productList = new ArrayList(); 16 | } 17 | 18 | /** 19 | * @return the productList 20 | */ 21 | public List getProductList() { 22 | return productList; 23 | } 24 | 25 | /** 26 | * @param productList the productList to set 27 | */ 28 | public void setProductList(List productList) { 29 | this.productList = productList; 30 | } 31 | 32 | public Product findProductByCode(String code){ 33 | for(Product product:productList){ 34 | if (product.getCode().equals(code)){ 35 | return product; 36 | } 37 | } 38 | return null; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /exam2/src/CurrentOrder.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | /** 6 | * @author Administrator 7 | * 8 | */ 9 | public class CurrentOrder { 10 | private BigDecimal orderTotal; 11 | private List orderItemList; 12 | /** 13 | * 14 | * @param initialList 15 | * @param initialBigDecimal 16 | */ 17 | // public CurrentOrder(List initialList, BigDecimal initialBigDecimal){ 18 | // this.setOrderItemList(initialList); 19 | // this.setOrderTotal(initialBigDecimal); 20 | // } 21 | public CurrentOrder(CurrentOrder _currentOrder){ 22 | this.orderItemList = new ArrayList(_currentOrder.getOrderItemList()); 23 | this.orderTotal = _currentOrder.getOrderTotal(); 24 | } 25 | public CurrentOrder(){ 26 | orderItemList = new ArrayList(); 27 | orderTotal = new BigDecimal("0"); 28 | } 29 | 30 | /** 31 | * @return the orderTotal 32 | */ 33 | public BigDecimal getOrderTotal() { 34 | return orderTotal; 35 | } 36 | 37 | /** 38 | * @param orderTotal the orderTotal to set 39 | */ 40 | public void setOrderTotal(BigDecimal orderTotal) { 41 | this.orderTotal = orderTotal; 42 | } 43 | 44 | /** 45 | * @return the orderItemList 46 | */ 47 | public List getOrderItemList() { 48 | return orderItemList; 49 | } 50 | 51 | /** 52 | * @param orderItemList the orderItemList to set 53 | */ 54 | public void setOrderItemList(List orderItemList) { 55 | this.orderItemList = orderItemList; 56 | } 57 | public String toString(){ 58 | String str = new String(); 59 | for (OrderItem item : orderItemList){ 60 | str = str + item.toString(); 61 | str = str + "\n"; 62 | } 63 | String s = "orderTotal = "; 64 | s = s + orderTotal; 65 | str = str + s; 66 | return str; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /exam2/src/Jelly.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.util.Date; 3 | 4 | /** 5 | * 6 | */ 7 | 8 | /** 9 | * @author Administrator 10 | * 11 | */ 12 | public class Jelly extends Product { 13 | private String type; 14 | private String diluteConcentration; 15 | /** 16 | * 17 | * @param initialCode 18 | * @param initialDescription 19 | * @param initialPrice 20 | * @param initialProductionDate 21 | * @param initialShelfLife 22 | * @param initialType 23 | * @param initialDiluteConcentration 24 | */ 25 | public Jelly(String initialCode, String initialDescription, 26 | BigDecimal initialPrice, Date initialProductionDate, 27 | String initialShelfLife, String initialType, String initialDiluteConcentration){ 28 | super(initialCode, initialDescription, initialPrice, initialProductionDate, initialShelfLife); 29 | type = initialType; 30 | diluteConcentration = initialDiluteConcentration; 31 | } 32 | /** 33 | * @return the type 34 | */ 35 | public String getType() { 36 | return type; 37 | } 38 | /** 39 | * @param type the type to set 40 | */ 41 | public void setType(String type) { 42 | this.type = type; 43 | } 44 | /** 45 | * @return the diluteConcentration 46 | */ 47 | public String getDiluteConcentration() { 48 | return diluteConcentration; 49 | } 50 | /** 51 | * @param diluteConcentration the diluteConcentration to set 52 | */ 53 | public void setDiluteConcentration(String diluteConcentration) { 54 | this.diluteConcentration = diluteConcentration; 55 | } 56 | /** 57 | * @return String 58 | */ 59 | public String toString(){ 60 | return "Jelly [" + super.toString() + ", Type = " + this.getType() 61 | + ", DiluteConcentration = " + this.getDiluteConcentration() + "]"; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /exam2/src/MilkDrink.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.util.Date; 3 | 4 | /** 5 | * 6 | */ 7 | 8 | /** 9 | * @author Grover Zhu 10 | * 11 | */ 12 | public class MilkDrink extends Product { 13 | private String flavor; 14 | private String sugar; 15 | /** 16 | * 17 | * @param initialCode 18 | * @param initialDescription 19 | * @param initialPrice 20 | * @param initialProductionDate 21 | * @param initialShelfLife 22 | * @param initialFlavor 23 | * @param initialSugar 24 | */ 25 | public MilkDrink(String initialCode, String initialDescription, 26 | BigDecimal initialPrice, Date initialProductionDate, String initialShelfLife, 27 | String initialFlavor, String initialSugar){ 28 | super(initialCode, initialDescription, initialPrice, initialProductionDate, initialShelfLife); 29 | flavor = initialFlavor; 30 | sugar = initialSugar; 31 | } 32 | /** 33 | * @return the flavor 34 | */ 35 | public String getFlavor() { 36 | return flavor; 37 | } 38 | /** 39 | * @param flavor the flavor to set 40 | */ 41 | public void setFlavor(String flavor) { 42 | this.flavor = flavor; 43 | } 44 | /** 45 | * @return the sugar 46 | */ 47 | public String getSugar() { 48 | return sugar; 49 | } 50 | /** 51 | * @param sugar the sugar to set 52 | */ 53 | public void setSugar(String sugar) { 54 | this.sugar = sugar; 55 | } 56 | public String toString(){ 57 | return "MilkDrink [" + super.toString() + ", Flavor = " + this.getFlavor() + ", Sugar = " + this.getSugar() + "]"; 58 | } 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /exam2/src/OrderItem.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Grover Zhu 3 | * 4 | */ 5 | public class OrderItem { 6 | private int quantity; 7 | private Product product; 8 | /** 9 | * 10 | * @param initialProduct 11 | * @param initialQuantity 12 | */ 13 | public OrderItem(Product initialProduct, int initialQuantity){ 14 | quantity = initialQuantity; 15 | product = initialProduct; 16 | } 17 | 18 | /** 19 | * @return quantity 20 | */ 21 | public int getQuantity(){ 22 | return this.quantity; 23 | } 24 | /** 25 | * 26 | * @param _quantity 27 | */ 28 | public void setQuantity(int _quantity){ 29 | quantity = _quantity; 30 | } 31 | /** 32 | * 33 | * @return product 34 | */ 35 | public Product getProduct(){ 36 | return product; 37 | } 38 | /** 39 | * 40 | * @param _product 41 | */ 42 | public void setProduct(Product _product){ 43 | product = _product; 44 | } 45 | /** 46 | * @return the attributes of the class 47 | */ 48 | public String toString(){ 49 | return "[ quantity = " + quantity + ", code = " + product.getCode() + 50 | ", description = " +product.getDescription() + "price = " + 51 | product.getPrice() + "]"; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /exam2/src/Product.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.util.Date; 3 | 4 | /** 5 | * @author Grover Zhu 6 | * 7 | */ 8 | public class Product { 9 | private String code; 10 | private String description; 11 | private BigDecimal price; 12 | private Date productionDate; 13 | private String ShelfLife; 14 | /** 15 | * 16 | * @param initialCode 17 | * @param initialDescription 18 | * @param initialPrice 19 | * @param initialProductionDate 20 | * @param initialShelfLife 21 | */ 22 | public Product(String initialCode, String initialDescription, 23 | BigDecimal initialPrice, Date initialProductionDate, String initialShelfLife){ 24 | code = initialCode; 25 | description = initialDescription; 26 | price = initialPrice; 27 | productionDate = initialProductionDate; 28 | ShelfLife = initialShelfLife; 29 | } 30 | /** 31 | * @return the code 32 | */ 33 | public String getCode() { 34 | return code; 35 | } 36 | /** 37 | * @param code the code to set 38 | */ 39 | public void setCode(String code) { 40 | this.code = code; 41 | } 42 | /** 43 | * @return the description 44 | */ 45 | public String getDescription() { 46 | return description; 47 | } 48 | /** 49 | * @param description the description to set 50 | */ 51 | public void setDescription(String description) { 52 | this.description = description; 53 | } 54 | /** 55 | * @return the price 56 | */ 57 | public BigDecimal getPrice() { 58 | return price; 59 | } 60 | /** 61 | * @param price the price to set 62 | */ 63 | public void setPrice(BigDecimal price) { 64 | this.price = price; 65 | } 66 | /** 67 | * @return the productionDate 68 | */ 69 | public Date getProductionDate() { 70 | return productionDate; 71 | } 72 | /** 73 | * @param productionDate the productionDate to set 74 | */ 75 | public void setProductionDate(Date productionDate) { 76 | this.productionDate = productionDate; 77 | } 78 | /** 79 | * @return the shelfLife 80 | */ 81 | public String getShelfLife() { 82 | return ShelfLife; 83 | } 84 | /** 85 | * @param shelfLife the shelfLife to set 86 | */ 87 | public void setShelfLife(String shelfLife) { 88 | ShelfLife = shelfLife; 89 | } 90 | /** 91 | * @return String Description of the product 92 | */ 93 | public String toString(){ 94 | return "code = " + this.getCode() + ", Description = " + this.getDescription() 95 | + ", ShelfLife = " + this.getShelfLife() 96 | + ", Price = " + this.getPrice() + ", ProductionDate = " + this.getProductionDate(); 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /exam2/src/PureMilk.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.util.Date; 3 | 4 | /** 5 | * @author Grover Zhu 6 | * 7 | */ 8 | public class PureMilk extends Product { 9 | private String countryOfOrigin; 10 | private String butterfat; 11 | private String Protein; 12 | /** 13 | * 14 | * @param initialCode 15 | * @param initialDescription 16 | * @param initialPrice 17 | * @param date 18 | * @param initialShelfLife 19 | * @param initialCountryOfOrigin 20 | * @param initialButterfat 21 | * @param initialProtein 22 | */ 23 | public PureMilk(String initialCode, String initialDescription, 24 | BigDecimal initialPrice, Date date, String initialShelfLife, 25 | String initialCountryOfOrigin, String initialButterfat, String initialProtein){ 26 | super(initialCode, initialDescription, initialPrice, date, initialShelfLife); 27 | countryOfOrigin = initialCountryOfOrigin; 28 | butterfat = initialButterfat; 29 | Protein = initialProtein; 30 | } 31 | /** 32 | * @return the countryOfOrigin 33 | */ 34 | public String getCountryOfOrigin() { 35 | return countryOfOrigin; 36 | } 37 | /** 38 | * @param countryOfOrigin the countryOfOrigin to set 39 | */ 40 | public void setCountryOfOrigin(String countryOfOrigin) { 41 | this.countryOfOrigin = countryOfOrigin; 42 | } 43 | /** 44 | * @return the butterfat 45 | */ 46 | public String getButterfat() { 47 | return butterfat; 48 | } 49 | /** 50 | * @param butterfat the butterfat to set 51 | */ 52 | public void setButterfat(String butterfat) { 53 | this.butterfat = butterfat; 54 | } 55 | /** 56 | * @return the protein 57 | */ 58 | public String getProtein() { 59 | return Protein; 60 | } 61 | /** 62 | * @param protein the protein to set 63 | */ 64 | public void setProtein(String protein) { 65 | Protein = protein; 66 | } 67 | public String toString(){ 68 | return "PureMilk [" + super.toString() + ", CountryOfOrigin = " + this.getCountryOfOrigin() + ", Butterfat = " 69 | + this.getButterfat() + ", Protein = " + this.getProtein() + "]"; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /exam2/src/Sale.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | 5 | /** 6 | * @author Grover Zhu 7 | * 8 | */ 9 | public class Sale { 10 | private List orderList; 11 | public Sale(){ 12 | orderList = new ArrayList(); 13 | } 14 | /** 15 | * @return the orderList 16 | */ 17 | public List getOrderList() { 18 | return orderList; 19 | } 20 | /** 21 | * @param orderList the orderList to set 22 | */ 23 | public void setOrderList(List orderList) { 24 | this.orderList = orderList; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /exam2/src/Yogurt.java: -------------------------------------------------------------------------------- 1 | import java.math.BigDecimal; 2 | import java.util.Date; 3 | 4 | /** 5 | * @author Grover Zhu 6 | * 7 | */ 8 | public class Yogurt extends Product { 9 | private String flavor; 10 | /** 11 | * 12 | * @param initialCode 13 | * @param initialDescription 14 | * @param initialPrice 15 | * @param initialProductionDate 16 | * @param initialShelfLife 17 | * @param initialFlavor 18 | */ 19 | public Yogurt(String initialCode, String initialDescription, 20 | BigDecimal initialPrice, Date initialProductionDate, String initialShelfLife, 21 | String initialFlavor){ 22 | super(initialCode, initialDescription, initialPrice, initialProductionDate, initialShelfLife); 23 | flavor = initialFlavor; 24 | } 25 | /** 26 | * @return the flavor 27 | */ 28 | public String getFlavor() { 29 | return flavor; 30 | } 31 | /** 32 | * @param flavor the flavor to set 33 | */ 34 | public void setFlavor(String flavor) { 35 | this.flavor = flavor; 36 | } 37 | public String toString(){ 38 | return "Yogurt [" + super.toString() + ", Flavor = " + this.getFlavor() + "]"; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /exam3.0/src/Rectangle.java: -------------------------------------------------------------------------------- 1 | 2 | public class Rectangle implements XMLElement, Shape { 3 | private double height; 4 | private double width; 5 | 6 | /** 7 | * @param initHeight 8 | * @param initWidth 9 | */ 10 | public Rectangle(double initHeight, double initWidth) throws IllegalArgumentException { 11 | if (initHeight <= 0 || initWidth <= 0) { 12 | throw new IllegalArgumentException("the parameter is negative!"); 13 | } 14 | height = initHeight; 15 | width = initWidth; 16 | } 17 | 18 | /** 19 | * the construction function is used for no formal parameter 20 | */ 21 | public Rectangle() { 22 | height = 0; 23 | width = 0; 24 | 25 | } 26 | 27 | /** 28 | * @return the height 29 | */ 30 | public double getHeight() { 31 | return height; 32 | } 33 | 34 | /** 35 | * @param height 36 | * the height to set 37 | */ 38 | public void setHeight(double height) throws IllegalArgumentException { 39 | if (height <= 0) { 40 | throw new IllegalArgumentException("the parameter is negative!"); 41 | } 42 | this.height = height; 43 | } 44 | 45 | /** 46 | * @return the width 47 | */ 48 | public double getWidth() { 49 | return width; 50 | } 51 | 52 | /** 53 | * @param width 54 | * the width to set 55 | */ 56 | public void setWidth(double width) { 57 | if (width <= 0) { 58 | throw new IllegalArgumentException("the parameter is negative!"); 59 | } 60 | this.width = width; 61 | } 62 | 63 | /** 64 | * judge the two object by their area, if two areas are equal then return 65 | * true, if not return false 66 | * 67 | * @param otherObject 68 | * @return boolean 69 | */ 70 | public boolean equal(Object otherObject) { 71 | if (otherObject instanceof Rectangle) { 72 | Rectangle otherRectangle = (Rectangle) otherObject; 73 | if (this.computeArea() == otherRectangle.computeArea()) { 74 | return true; 75 | } 76 | } 77 | return false; 78 | } 79 | 80 | /** 81 | * @return area 82 | */ 83 | public double computeArea() { 84 | return this.height * this.width; 85 | } 86 | 87 | /** 88 | * using the XML format to print the information of the object 89 | * 90 | * @return String 91 | */ 92 | public String getXML() { 93 | String XMLFormat = new String(); 94 | XMLFormat = "\n"; 95 | XMLFormat = XMLFormat + "" + this.getHeight() + "\n"; 96 | XMLFormat = XMLFormat + "" + this.getWidth() + "\n"; 97 | XMLFormat = XMLFormat + "\n"; 98 | return XMLFormat; 99 | } 100 | 101 | public static void main(String[] args) { 102 | Rectangle rectangle1 = new Rectangle(2.1, 2.0); 103 | Rectangle rectangle2 = new Rectangle(2.1, 2.0); 104 | System.out.println(rectangle1.getXML()); 105 | System.out.println(rectangle1.equal(rectangle2)); 106 | // Rectangle rectangle3 = new Rectangle(); 107 | // Rectangle rectangle4 = new Rectangle(); 108 | // rectangle3.setHeight(-0.1); 109 | // rectangle3.setWidth(0.1); 110 | // rectangle4.setHeight(0.1); 111 | // rectangle4.setWidth(-0.1); 112 | // Rectangle rectangle5 = new Rectangle(-2.1, 2.1); 113 | 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /exam3.0/src/Shape.java: -------------------------------------------------------------------------------- 1 | 2 | public interface Shape { 3 | double computeArea(); 4 | } 5 | -------------------------------------------------------------------------------- /exam3.0/src/XMLElement.java: -------------------------------------------------------------------------------- 1 | 2 | public interface XMLElement { 3 | String getXML(); 4 | } 5 | -------------------------------------------------------------------------------- /exam3.1/classFile/Catalog.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam3.1/classFile/Catalog.class -------------------------------------------------------------------------------- /exam3.1/classFile/CurrentOrder.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam3.1/classFile/CurrentOrder.class -------------------------------------------------------------------------------- /exam3.1/classFile/Jelly.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam3.1/classFile/Jelly.class -------------------------------------------------------------------------------- /exam3.1/classFile/MilkDrink.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam3.1/classFile/MilkDrink.class -------------------------------------------------------------------------------- /exam3.1/classFile/OrderItem.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam3.1/classFile/OrderItem.class -------------------------------------------------------------------------------- /exam3.1/classFile/Product.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam3.1/classFile/Product.class -------------------------------------------------------------------------------- /exam3.1/classFile/PureMilk.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam3.1/classFile/PureMilk.class -------------------------------------------------------------------------------- /exam3.1/classFile/Sale.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam3.1/classFile/Sale.class -------------------------------------------------------------------------------- /exam3.1/classFile/Yogurt.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam3.1/classFile/Yogurt.class -------------------------------------------------------------------------------- /exam3.1/src/BrightFreshMilk.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | import java.io.PrintWriter; 5 | import java.math.BigDecimal; 6 | import java.util.ArrayList; 7 | import java.util.Date; 8 | import java.util.List; 9 | 10 | /** 11 | * This class implements a Bright Fresh Milk System. 12 | * 13 | * @author Grover Zhu 14 | * @version 1.1.0 15 | */ 16 | public class BrightFreshMilk { 17 | 18 | private static BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); 19 | private static PrintWriter stdOut = new PrintWriter(System.out, true); 20 | private static PrintWriter stdErr = new PrintWriter(System.err, true); 21 | 22 | private Sale sales; 23 | 24 | private SalesFormatter salesFormatter; 25 | 26 | /** 27 | * Loads data into the catalog and starts the application. 28 | * 29 | * @param args 30 | * String arguments. Not used. 31 | * @throws IOException 32 | * if there are errors in the input. 33 | */ 34 | public static void main(String[] args) throws IOException { 35 | 36 | BrightFreshMilk application = new BrightFreshMilk(); 37 | application.run(); 38 | 39 | } 40 | 41 | /** 42 | * Constructs a GourmetCoffee object and initializes the 43 | * catalog and sales data. 44 | * 45 | * @param initialCatalog 46 | * a product catalog 47 | */ 48 | private BrightFreshMilk() { 49 | 50 | this.sales = new Sale(); 51 | 52 | this.salesFormatter = PlainTextSalesFormatter.getSingletonInstance(); 53 | 54 | loadSales(loadCatalog()); 55 | } 56 | 57 | /** 58 | * Creates an empty catalog and then add products to it. 59 | * 60 | * @return a product catalog 61 | */ 62 | private Catalog loadCatalog() { 63 | 64 | Catalog catalog = new Catalog(); 65 | List productList = new ArrayList(); 66 | 67 | productList.add(new PureMilk("A001", "milk,400ml", new BigDecimal("10"), new Date(), "25 days", "China", "3.5%", 68 | "2.9%")); 69 | productList.add(new PureMilk("A002", "skim milk,800ml", new BigDecimal("18"), new Date(), "30 days", "China", 70 | "3.1%", "3.9%")); 71 | 72 | productList.add(new Jelly("B001", "solid,250ml", new BigDecimal("8.5"), new Date(), "15 days", "solid", "80%")); 73 | productList.add(new Jelly("B002", "solid,400ml", new BigDecimal("14"), new Date(), "16 days", "solid", "85%")); 74 | 75 | productList.add( 76 | new Yogurt("C001", "chocolate flavor,270ml", new BigDecimal("5"), new Date(), "40 days", "chocolate")); 77 | productList.add(new Yogurt("C002", "strawberry flavor,400ml", new BigDecimal("10"), new Date(), "40 days", 78 | "strawberry")); 79 | 80 | productList.add(new MilkDrink("D001", "taro flavor,250ml", new BigDecimal("13.1"), new Date(), "25 days", 81 | "taro", "2.9%")); 82 | productList.add(new MilkDrink("D002", "apple flavor,400ml", new BigDecimal("16"), new Date(), "30 days", 83 | "apple", "3.8%")); 84 | 85 | catalog.setProductList(productList); 86 | return catalog; 87 | } 88 | 89 | /** 90 | * Initializes the sales object. 91 | */ 92 | private void loadSales(Catalog catalog) { 93 | 94 | List orderList = new ArrayList(); 95 | 96 | CurrentOrder orderOne = new CurrentOrder(); 97 | List orderItemList = new ArrayList(); 98 | orderItemList.add(new OrderItem(catalog.findProductByCode("C001"), 5)); 99 | orderOne.setOrderItemList(orderItemList); 100 | orderOne.setOrderTotal(new BigDecimal("25")); 101 | orderList.add(orderOne); 102 | 103 | CurrentOrder orderTwo = new CurrentOrder(); 104 | List orderItemListTwo = new ArrayList(); 105 | orderItemListTwo.add(new OrderItem(catalog.findProductByCode("C002"), 2)); 106 | orderItemListTwo.add(new OrderItem(catalog.findProductByCode("A001"), 2)); 107 | orderTwo.setOrderItemList(orderItemListTwo); 108 | orderTwo.setOrderTotal(new BigDecimal("40")); 109 | orderList.add(orderTwo); 110 | 111 | CurrentOrder orderThree = new CurrentOrder(); 112 | List orderItemListThree = new ArrayList(); 113 | orderItemListThree.add(new OrderItem(catalog.findProductByCode("B002"), 1)); 114 | orderThree.setOrderItemList(orderItemListThree); 115 | orderThree.setOrderTotal(new BigDecimal("14")); 116 | orderList.add(orderThree); 117 | 118 | sales.setOrderList(orderList); 119 | } 120 | 121 | /** 122 | * Displays a menu of options and verifies the user's choice. 123 | * 124 | * @return an integer in the range [0,3] 125 | */ 126 | private int getChoice() throws IOException { 127 | 128 | int input; 129 | 130 | do { 131 | try { 132 | stdErr.println(); 133 | stdErr.print("[0] Quit\n" + "[1] Display sales (Plain Text)\n" + "[2] Display sales (HTML)\n" 134 | + "[3] Display sales (XML)\n" + "choice> "); 135 | stdErr.flush(); 136 | 137 | input = Integer.parseInt(stdIn.readLine()); 138 | 139 | stdErr.println(); 140 | 141 | if (0 <= input && 3 >= input) { 142 | break; 143 | } else { 144 | stdErr.println("Invalid choice: " + input); 145 | } 146 | } catch (NumberFormatException nfe) { 147 | stdErr.println(nfe); 148 | } 149 | } while (true); 150 | 151 | return input; 152 | } 153 | 154 | /** 155 | * Changes the sales formatter. 156 | * 157 | * @param newFormatter 158 | * a sales formatter 159 | */ 160 | private void setSalesFormatter(SalesFormatter newFormatter) { 161 | salesFormatter = newFormatter; 162 | } 163 | 164 | /** 165 | * Displays the sales information in the current format. 166 | */ 167 | private void displaySales() { 168 | stdOut.println(salesFormatter.formatSales(sales)); 169 | } 170 | 171 | /** 172 | * Presents the user with a menu of options and executes the selected task. 173 | */ 174 | private void run() throws IOException { 175 | int choice = getChoice(); 176 | SalesFormatter newSalesFormatter; 177 | while (choice != 0){ 178 | if (choice == 1){ 179 | newSalesFormatter = PlainTextSalesFormatter.getSingletonInstance(); 180 | setSalesFormatter(newSalesFormatter); 181 | displaySales(); 182 | }else if (choice == 2){ 183 | newSalesFormatter = HTMLSalesFormatter.getSingletonInstance(); 184 | setSalesFormatter(newSalesFormatter); 185 | displaySales(); 186 | }else if(choice == 3){ 187 | newSalesFormatter = XMLSalesFormatter.getSingletonInstance(); 188 | setSalesFormatter(newSalesFormatter); 189 | displaySales(); 190 | } 191 | choice = getChoice(); 192 | } 193 | } 194 | } -------------------------------------------------------------------------------- /exam3.1/src/HTMLSalesFormatter.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public class HTMLSalesFormatter implements SalesFormatter { 4 | private static HTMLSalesFormatter singletonInstance; 5 | /** 6 | * 7 | * @return html sales formatter 8 | */ 9 | public static HTMLSalesFormatter getSingletonInstance() { 10 | if (singletonInstance == null) { 11 | singletonInstance = new HTMLSalesFormatter(); 12 | } 13 | return singletonInstance; 14 | } 15 | HTMLSalesFormatter() { 16 | } 17 | 18 | 19 | public String formatSales(Sale sales) { 20 | String HTML = new String( 21 | "\n \n\t

Orders

\n"); 22 | List orderList = sales.getOrderList(); 23 | for (CurrentOrder order : orderList) { 24 | HTML = HTML + "\t
\n\t

Total = " + order.getOrderTotal() 25 | + "

\n"; 26 | List items = order.getOrderItemList(); 27 | for (OrderItem item : items) { 28 | HTML = HTML + "\t

\n\t\tcode:" 29 | + item.getProduct().getCode() + "
\n"; 30 | HTML = HTML + "\t\tquantity: " + item.getQuantity() 31 | + "
\n"; 32 | HTML = HTML + "\t\tprice: " + item.getProduct().getPrice() 33 | + "\n"; 34 | HTML = HTML + "\t

\n"; 35 | } 36 | } 37 | HTML = HTML + " \n"; 38 | return HTML; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /exam3.1/src/PlainTextSalesFormatter.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class PlainTextSalesFormatter implements SalesFormatter { 4 | private static PlainTextSalesFormatter singletonInstance; 5 | 6 | public static PlainTextSalesFormatter getSingletonInstance() { 7 | if (singletonInstance == null) { 8 | singletonInstance = new PlainTextSalesFormatter(); 9 | } 10 | return singletonInstance; 11 | } 12 | 13 | 14 | private PlainTextSalesFormatter() { 15 | // TODO Auto-generated constructor stub 16 | } 17 | 18 | public String formatSales(Sale sales) { 19 | String plainText = new String(); 20 | String dashLine = new String("------------------------"); 21 | List orderList = sales.getOrderList(); 22 | int number = 1; 23 | for (CurrentOrder order : orderList) { 24 | plainText = plainText + dashLine + "\n"; 25 | plainText = plainText + "Order " + number + "\n\n"; 26 | List items = order.getOrderItemList(); 27 | for (OrderItem item : items) { 28 | plainText = plainText + item.getQuantity() + " " 29 | + item.getProduct().getCode() + " " 30 | + item.getProduct().getPrice() + "\n\n"; 31 | } 32 | plainText = plainText + "Total = " + order.getOrderTotal() + "\n"; 33 | 34 | number++; 35 | } 36 | return plainText; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /exam3.1/src/SalesFormatter.java: -------------------------------------------------------------------------------- 1 | 2 | public interface SalesFormatter { 3 | String formatSales(Sale sales); 4 | } 5 | -------------------------------------------------------------------------------- /exam3.1/src/XMLSalesFormatter.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public class XMLSalesFormatter implements SalesFormatter { 4 | private static XMLSalesFormatter singletonInstance; 5 | 6 | public static XMLSalesFormatter getSingletonInstance() { 7 | if (singletonInstance == null) { 8 | singletonInstance = new XMLSalesFormatter(); 9 | } 10 | return singletonInstance; 11 | } 12 | 13 | public XMLSalesFormatter() { 14 | } 15 | 16 | public String formatSales(Sale sales) { 17 | String XML = new String("\n"); 18 | List orderList = sales.getOrderList(); 19 | for (CurrentOrder order : orderList) { 20 | XML = XML + " < Order total = " + order.getOrderTotal() + ">\n"; 21 | List items = order.getOrderItemList(); 22 | for (OrderItem item : items) { 23 | XML = XML + "\t quantity = \"" + item.getQuantity() 24 | + "\" price = \"" + item.getProduct().getPrice() 25 | + "\">" + item.getProduct().getCode() 26 | + "\n"; 27 | } 28 | XML = XML + " \n"; 29 | } 30 | XML = XML + ""; 31 | return XML; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /exam4.0/catalog.dat: -------------------------------------------------------------------------------- 1 | PureMilk_A001_milk,400ml_10_2017-10-20_25 days_China_3.5%_2.9% 2 | PureMilk_A002_skim milk,800ml_18_2017-10-20_30 days_China_3.1%_3.9% 3 | Jelly_B001_solid,250ml_8.5_2017-10-20_15 days_solid_80% 4 | Jelly_B002_solid,400ml_14_2017-10-20_16 days_solid_85% 5 | Yogurt_C001_chocolate flavor,270ml_5_2017-10-20_40 days_chocolate 6 | Yogurt_C002_strawberry flavor,400ml_10_2017-10-20_40 days_strawberry 7 | MilkDrink_D001_taro flavor,250ml_13.1_2017-10-20_25 days_taro_2.9% 8 | MilkDrink_D002_apple flavor,400ml_16_2017-10-20_30 days_apple_3.8% -------------------------------------------------------------------------------- /exam4.0/classFiles/Catalog.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/Catalog.class -------------------------------------------------------------------------------- /exam4.0/classFiles/CurrentOrder.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/CurrentOrder.class -------------------------------------------------------------------------------- /exam4.0/classFiles/HTMLSalesFormatter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/HTMLSalesFormatter.class -------------------------------------------------------------------------------- /exam4.0/classFiles/Jelly.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/Jelly.class -------------------------------------------------------------------------------- /exam4.0/classFiles/MilkDrink.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/MilkDrink.class -------------------------------------------------------------------------------- /exam4.0/classFiles/OrderItem.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/OrderItem.class -------------------------------------------------------------------------------- /exam4.0/classFiles/PlainTextSalesFormatter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/PlainTextSalesFormatter.class -------------------------------------------------------------------------------- /exam4.0/classFiles/Product.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/Product.class -------------------------------------------------------------------------------- /exam4.0/classFiles/PureMilk.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/PureMilk.class -------------------------------------------------------------------------------- /exam4.0/classFiles/Sale.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/Sale.class -------------------------------------------------------------------------------- /exam4.0/classFiles/SalesFormatter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/SalesFormatter.class -------------------------------------------------------------------------------- /exam4.0/classFiles/XMLSalesFormatter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/XMLSalesFormatter.class -------------------------------------------------------------------------------- /exam4.0/classFiles/XMLSalesFormatter.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public class XMLSalesFormatter implements SalesFormatter { 4 | private static XMLSalesFormatter singletonInstance; 5 | 6 | public static XMLSalesFormatter getSingletonInstance() { 7 | if (singletonInstance == null) { 8 | singletonInstance = new XMLSalesFormatter(); 9 | } 10 | return singletonInstance; 11 | } 12 | 13 | public XMLSalesFormatter() { 14 | } 15 | 16 | public String formatSales(Sale sales) { 17 | String XML = new String("\n"); 18 | List orderList = sales.getOrderList(); 19 | for (CurrentOrder order : orderList) { 20 | XML = XML + " \n"; 21 | List items = order.getOrderItemList(); 22 | for (OrderItem item : items) { 23 | XML = XML + "\t quantity = \"" + item.getQuantity() 24 | + "\" price = \"" + item.getProduct().getPrice() 25 | + "\">" + item.getProduct().getCode() 26 | + "\n"; 27 | } 28 | XML = XML + " \n"; 29 | } 30 | XML = XML + ""; 31 | return XML; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /exam4.0/classFiles/Yogurt.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/classFiles/Yogurt.class -------------------------------------------------------------------------------- /exam4.0/empty.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.0/empty.dat -------------------------------------------------------------------------------- /exam4.0/src/BrightFreshMilk.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.File; 3 | import java.io.FileNotFoundException; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.io.InputStreamReader; 7 | import java.io.PrintWriter; 8 | import java.math.BigDecimal; 9 | import java.text.ParseException; 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * This class implements a Bright Fresh Milk system. 15 | * 16 | */ 17 | public class BrightFreshMilk { 18 | 19 | private static BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); 20 | private static PrintWriter stdOut = new PrintWriter(System.out, true); 21 | private static PrintWriter stdErr = new PrintWriter(System.err, true); 22 | 23 | private Catalog catalog; 24 | private Sale sales; 25 | 26 | private SalesFormatter salesFormatter; 27 | 28 | /** 29 | * Loads catalog data from a file and starts the application. 30 | *

31 | * The name of the file is specified in the command arguments. 32 | *

33 | * 34 | * @param args 35 | * String arguments. 36 | * @throws IOException 37 | * if there are errors in the input. 38 | */ 39 | public static void main(String[] args) throws IOException { 40 | 41 | Catalog catalog = null; 42 | 43 | if (args.length != 1) { 44 | stdErr.println("Usage: java BrightFreshMilk filename"); 45 | } else { 46 | try { 47 | catalog = (new FileCatalogLoader()).loadCatalog(args[0]); 48 | } catch (FileNotFoundException fnfe) { 49 | stdErr.println("The file does not exist"); 50 | 51 | System.exit(1); 52 | 53 | } catch (DataFormatException dfe) { 54 | stdErr.println("The file contains malformed data: " + dfe.getMessage()); 55 | 56 | System.exit(1); 57 | } catch (ParseException e) { 58 | stdErr.println(e.getMessage()); 59 | 60 | System.exit(1); 61 | } 62 | 63 | BrightFreshMilk application = new BrightFreshMilk(catalog); 64 | 65 | application.run(); 66 | } 67 | } 68 | 69 | /** 70 | * Initializes the catalog data with the value specified in the parameter. 71 | * 72 | * @param initialCatalog 73 | * a product catalog 74 | */ 75 | private BrightFreshMilk(Catalog initialCatalog) { 76 | 77 | this.catalog = initialCatalog; 78 | this.sales = new Sale(); 79 | this.salesFormatter = PlainTextSalesFormatter.getSingletonInstance(); 80 | 81 | loadSales(); 82 | } 83 | 84 | /** 85 | * Initializes the sales object. 86 | */ 87 | private void loadSales() { 88 | 89 | List orderList = new ArrayList(); 90 | 91 | CurrentOrder orderOne = new CurrentOrder(); 92 | List orderItemList = new ArrayList(); 93 | orderItemList.add(new OrderItem(catalog.findProductByCode("C001"), 5)); 94 | orderOne.setOrderItemList(orderItemList); 95 | orderOne.setOrderTotal(new BigDecimal("25")); 96 | orderList.add(orderOne); 97 | 98 | CurrentOrder orderTwo = new CurrentOrder(); 99 | List orderItemListTwo = new ArrayList(); 100 | orderItemListTwo.add(new OrderItem(catalog.findProductByCode("C002"), 2)); 101 | orderItemListTwo.add(new OrderItem(catalog.findProductByCode("A001"), 2)); 102 | orderTwo.setOrderItemList(orderItemListTwo); 103 | orderTwo.setOrderTotal(new BigDecimal("40")); 104 | orderList.add(orderTwo); 105 | 106 | CurrentOrder orderThree = new CurrentOrder(); 107 | List orderItemListThree = new ArrayList(); 108 | orderItemListThree.add(new OrderItem(catalog.findProductByCode("B002"), 1)); 109 | orderThree.setOrderItemList(orderItemListThree); 110 | orderThree.setOrderTotal(new BigDecimal("14")); 111 | orderList.add(orderThree); 112 | 113 | sales.setOrderList(orderList); 114 | } 115 | 116 | /** 117 | * Presents the user with a menu of options and executes the selected task. 118 | */ 119 | private void run() throws IOException { 120 | 121 | int choice = getChoice(); 122 | 123 | while (choice != 0) { 124 | if (choice == 1) { 125 | displayCatalog(); 126 | } else if (choice == 2) { 127 | this.salesFormatter = PlainTextSalesFormatter.getSingletonInstance(); 128 | writeFile(readFilename(), this.salesFormatter.formatSales(this.sales)); 129 | } else if (choice == 3) { 130 | this.salesFormatter = HTMLSalesFormatter.getSingletonInstance(); 131 | writeFile(readFilename(), this.salesFormatter.formatSales(this.sales)); 132 | } else if (choice == 4) { 133 | this.salesFormatter = XMLSalesFormatter.getSingletonInstance(); 134 | writeFile(readFilename(), this.salesFormatter.formatSales(this.sales)); 135 | } 136 | 137 | choice = getChoice(); 138 | } 139 | } 140 | 141 | /** 142 | * Displays a menu of options and verifies the user's choice. 143 | * 144 | * @return an integer in the range [0,4] 145 | */ 146 | private int getChoice() throws IOException { 147 | 148 | int input; 149 | 150 | do { 151 | try { 152 | stdErr.println(); 153 | stdErr.print("[0] Quit\n" + "[1] Display Catalog\n" + "[2] Save sales (Plain Text)\n" 154 | + "[3] Save sales (HTML)\n" + "[4] Save sales (XML)\n" + "choice> "); 155 | stdErr.flush(); 156 | 157 | input = Integer.parseInt(stdIn.readLine()); 158 | 159 | stdErr.println(); 160 | 161 | if (0 <= input && 4 >= input) { 162 | break; 163 | } else { 164 | stdErr.println("Invalid choice: " + input); 165 | } 166 | } catch (NumberFormatException nfe) { 167 | stdErr.println(nfe); 168 | } 169 | } while (true); 170 | 171 | return input; 172 | } 173 | 174 | /** 175 | * Displays the catalog. 176 | */ 177 | private void displayCatalog() { 178 | 179 | int size = this.catalog.getProductList().size(); 180 | 181 | if (size == 0) { 182 | stdErr.println("The catalog is empty"); 183 | } else { 184 | for (Product product : this.catalog.getProductList()) { 185 | stdOut.println(product.getCode() + " " + product.getDescription() + " " + product.getPrice()); 186 | } 187 | } 188 | } 189 | 190 | /** 191 | * Creates a new file (which has the specified name) and writes the 192 | * specified string to the new file. 193 | * 194 | * @param filename 195 | * name of the file that will store the data 196 | * @param content 197 | * data to be stored 198 | */ 199 | private void writeFile(String filename, String content) throws IOException { 200 | FileWriter file = new FileWriter(new File(filename)); 201 | file.write(content); 202 | file.close(); 203 | //to do 204 | } 205 | 206 | /** 207 | * Prompts the user for a filename (the name of the file that will store the 208 | * sales information) and returns the user's response. 209 | * 210 | * @return name of a file 211 | */ 212 | private String readFilename() throws IOException { 213 | 214 | stdErr.print("Filename> "); 215 | stdErr.flush(); 216 | 217 | return stdIn.readLine(); 218 | } 219 | } -------------------------------------------------------------------------------- /exam4.0/src/CatalogLoader.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.text.ParseException; 3 | 4 | /** 5 | * This interface declares a method for obtaining a products catalog. 6 | * 7 | * @author iCarnegie 8 | * @version 1.1.0 9 | * @see Catalog 10 | */ 11 | public interface CatalogLoader { 12 | 13 | /* 14 | * Loads the product catalog with the data in the specified file. 15 | * 16 | * @param filename The name of a file that contains catalog information. 17 | * 18 | * @return the product catalog. 19 | * 20 | * @throws FileNotFoundException if the specified file does not exist. 21 | * 22 | * @throws IOException if there is an error reading the information in the 23 | * specified file. 24 | * 25 | * @throws DataFormatException if the file contains badly-formed data. 26 | * 27 | * @throws ParseException if the date contains badly-formed data. 28 | */ 29 | Catalog loadCatalog(String fileName) throws FileNotFoundException, IOException, DataFormatException, ParseException; 30 | } -------------------------------------------------------------------------------- /exam4.0/src/DataFormatException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This exception is thrown when malformed data is detected while 3 | * a file being parsed. 4 | * 5 | * @author iCarnegie 6 | * @version 1.0.0 7 | */ 8 | public class DataFormatException extends Exception { 9 | 10 | /** 11 | * Constructs a DataFormatException with no detail 12 | * message. 13 | */ 14 | public DataFormatException() { 15 | 16 | } 17 | 18 | /** 19 | * Constructs a DataFormatException with the 20 | * specified detail message. 21 | * 22 | * @param message the malformed data 23 | */ 24 | public DataFormatException(String message) { 25 | 26 | super(message); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /exam4.0/src/FileCatalogLoader.java: -------------------------------------------------------------------------------- 1 | import java.text.ParseException; 2 | import java.text.SimpleDateFormat; 3 | import java.util.*; 4 | import java.util.StringTokenizer; 5 | import java.io.*; 6 | import java.math.BigDecimal; 7 | import java.sql.Date; 8 | /** 9 | * @author Grover Zhu 10 | * 11 | */ 12 | public class FileCatalogLoader implements CatalogLoader { 13 | 14 | public Catalog loadCatalog(String fileName) 15 | throws FileNotFoundException, IOException, DataFormatException, ParseException { 16 | // TODO Auto-generated method stub 17 | File file = new File(fileName); 18 | List catalog = new ArrayList(); 19 | BufferedReader bufferedReader = new BufferedReader(new FileReader(file)); 20 | String line = null; 21 | line = bufferedReader.readLine(); 22 | while (line != null){ 23 | StringTokenizer st = new StringTokenizer(line,"_"); 24 | String s = st.nextToken(); 25 | if (s.equals("PureMilk")){ 26 | catalog.add(readPureMilk(line)); 27 | }else if (s.equals("Jelly")){ 28 | catalog.add(readJelly(line)); 29 | }else if (s.equals("Yogurt")){ 30 | catalog.add(readYogurt(line)); 31 | }else if (s.equals("MilkDrink")){ 32 | catalog.add(readMilkDrink(line)); 33 | } 34 | line = bufferedReader.readLine(); 35 | } 36 | bufferedReader.close(); 37 | Catalog catalogs = new Catalog(catalog); 38 | return catalogs; 39 | } 40 | 41 | private PureMilk readPureMilk (String line) throws DataFormatException, ParseException{ 42 | StringTokenizer stringTokenizer = new StringTokenizer(line, "_"); 43 | if(stringTokenizer.countTokens()!=9){ 44 | throw new DataFormatException(line); 45 | }else{ 46 | stringTokenizer.nextToken(); 47 | PureMilk pureMilk = new PureMilk(stringTokenizer.nextToken(),stringTokenizer.nextToken(),new BigDecimal(stringTokenizer.nextToken()), 48 | new SimpleDateFormat("yyyy-MM-dd").parse(stringTokenizer.nextToken()),stringTokenizer.nextToken(),stringTokenizer.nextToken(),stringTokenizer.nextToken(),stringTokenizer.nextToken()); 49 | return pureMilk; 50 | } 51 | 52 | } 53 | 54 | private Jelly readJelly(String line) throws DataFormatException, ParseException { 55 | StringTokenizer stringTokenizer = new StringTokenizer(line, "_"); 56 | if(stringTokenizer.countTokens()!=8){ 57 | throw new DataFormatException(line); 58 | }else{ 59 | stringTokenizer.nextToken(); 60 | Jelly jelly = new Jelly(stringTokenizer.nextToken(),stringTokenizer.nextToken(),new BigDecimal(stringTokenizer.nextToken()), 61 | new SimpleDateFormat("yyyy-MM-dd").parse(stringTokenizer.nextToken()),stringTokenizer.nextToken(),stringTokenizer.nextToken(),stringTokenizer.nextToken()); 62 | return jelly; 63 | } 64 | } 65 | 66 | private Yogurt readYogurt(String line) throws DataFormatException, ParseException { 67 | StringTokenizer stringTokenizer = new StringTokenizer(line, "_"); 68 | if(stringTokenizer.countTokens()!=7){ 69 | throw new DataFormatException(line); 70 | }else{ 71 | stringTokenizer.nextToken(); 72 | Yogurt yogurt = new Yogurt(stringTokenizer.nextToken(),stringTokenizer.nextToken(),new BigDecimal(stringTokenizer.nextToken()), 73 | new SimpleDateFormat("yyyy-MM-dd").parse(stringTokenizer.nextToken()),stringTokenizer.nextToken(),stringTokenizer.nextToken()); 74 | return yogurt; 75 | } 76 | } 77 | 78 | private MilkDrink readMilkDrink(String line) throws DataFormatException, ParseException { 79 | StringTokenizer stringTokenizer = new StringTokenizer(line, "_"); 80 | if(stringTokenizer.countTokens()!=8){ 81 | throw new DataFormatException(line); 82 | }else{ 83 | stringTokenizer.nextToken(); 84 | MilkDrink milkDrink = new MilkDrink(stringTokenizer.nextToken(),stringTokenizer.nextToken(),new BigDecimal(stringTokenizer.nextToken()), 85 | new SimpleDateFormat("yyyy-MM-dd").parse(stringTokenizer.nextToken()),stringTokenizer.nextToken(),stringTokenizer.nextToken(),stringTokenizer.nextToken()); 86 | return milkDrink; 87 | } 88 | } 89 | 90 | 91 | } 92 | -------------------------------------------------------------------------------- /exam4.0/src/TestFileCatalogLoader.java: -------------------------------------------------------------------------------- 1 | import java.io.IOException; 2 | import java.io.PrintWriter; 3 | import java.math.BigDecimal; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | 7 | /** 8 | * Tests the class FileCatalogLoader 9 | * 10 | * @author iCarnegie 11 | * @version 1.0.0 12 | * @see FileCatalogLoader 13 | */ 14 | public class TestFileCatalogLoader { 15 | 16 | /* Standard output stream */ 17 | private static PrintWriter stdOut = new PrintWriter(System.out, true); 18 | 19 | /* Standard error stream */ 20 | private static PrintWriter stdErr = new PrintWriter(System.err, true); 21 | 22 | /** 23 | * Tests methods of class {@link FileCatalogLoader} 24 | * 25 | * @param args 26 | * not used. 27 | * @throws IOException 28 | * if an I/O error occurs. 29 | */ 30 | public static void main(String args[]) throws IOException { 31 | 32 | stdOut.println(""); 33 | stdOut.println("Testing class FileCatalogLoader..."); 34 | 35 | TestFileCatalogLoader tester = new TestFileCatalogLoader(); 36 | 37 | tester.testLoadCatalog(); 38 | stdOut.println("All tests passed"); 39 | stdOut.println(""); 40 | } 41 | 42 | /** 43 | * Displays a message in the standard error stream if the value specified by 44 | * parameter condition is false. 45 | * 46 | * @param message 47 | * the error message. 48 | * @param condition 49 | * the test condition. 50 | * @return the value of condition 51 | */ 52 | public static void assertTrue(String message, boolean condition) { 53 | 54 | if (!condition) { 55 | stdErr.print("** Test failure "); 56 | stdErr.println(message); 57 | 58 | System.exit(1); 59 | } 60 | 61 | } 62 | 63 | /** 64 | * Displays a message in the standard error stream. 65 | * 66 | * @param message 67 | * the error message. 68 | * @return false; 69 | */ 70 | public static void fail(String message) { 71 | 72 | stdErr.print("** Test failure "); 73 | stdErr.println(message); 74 | 75 | System.exit(1); 76 | } 77 | 78 | /** 79 | * Tests the method loadCatalog. 80 | * 81 | * @return true if all test passed; otherwise returns 82 | * false. 83 | * @throws IOException 84 | * if an I/O error occurs. 85 | */ 86 | public void testLoadCatalog() throws IOException { 87 | 88 | CatalogLoader loader = new FileCatalogLoader(); 89 | 90 | try { 91 | // Testing an empty file 92 | Catalog emptyCatalog = loader.loadCatalog("empty.dat"); 93 | 94 | assertTrue("1, testing method read with an empty file", emptyCatalog instanceof Catalog); 95 | assertTrue("2, testing method read with an empty file" + emptyCatalog.getProductList().size() 96 | + " products loaded", emptyCatalog.getProductList().size() == 0); 97 | 98 | // Testing a not empty file 99 | Catalog catalog = loader.loadCatalog("catalog.dat"); 100 | 101 | assertTrue("3, testing method loadCatalog", catalog instanceof Catalog); 102 | assertTrue("4, testing method loadCatalog: " + catalog.getProductList().size() + " products loaded", 103 | catalog.getProductList().size() == 8); 104 | 105 | // Testing product C001 106 | Product product = catalog.findProductByCode("C001"); 107 | 108 | assertTrue("5, testing method loadCatalog" + product.toString(), product instanceof Yogurt); 109 | 110 | Yogurt yogurtC001 = (Yogurt) product; 111 | 112 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 113 | assertTrue("6, testing method loadCatalog: " + yogurtC001.toString(), 114 | yogurtC001.getCode().equals("C001") && yogurtC001.getDescription().equals("chocolate flavor,270ml") 115 | && yogurtC001.getPrice().equals(new BigDecimal("5")) 116 | && yogurtC001.getProductionDate().equals(sdf.parse("2017-10-20")) 117 | && yogurtC001.getShelfLife().equals("40 days") 118 | && yogurtC001.getFlavor().equals("chocolate")); 119 | 120 | // Testing product C002 121 | 122 | product = catalog.findProductByCode("C002"); 123 | 124 | assertTrue("7, testing method loadCatalog" + product.toString(), product instanceof Yogurt); 125 | 126 | Yogurt yogurtC002 = (Yogurt) product; 127 | 128 | assertTrue("8, testing method loadCatalog: " + yogurtC002.toString(), 129 | yogurtC002.getCode().equals("C002") && yogurtC002.getDescription().equals("strawberry flavor,400ml") 130 | && yogurtC002.getPrice().equals(new BigDecimal("10")) 131 | && yogurtC002.getProductionDate().equals(sdf.parse("2017-10-20")) 132 | && yogurtC002.getShelfLife().equals("40 days") 133 | && yogurtC002.getFlavor().equals("strawberry")); 134 | 135 | // Testing product A001 136 | product = catalog.findProductByCode("A001"); 137 | 138 | assertTrue("9, testing method loadCatalog: " + product.toString(), product instanceof PureMilk); 139 | 140 | assertTrue("10, testing method loadCatalog: " + product.toString(), 141 | product.getCode().equals("A001") && product.getDescription().equals("milk,400ml") 142 | && product.getPrice().equals(new BigDecimal("10"))); 143 | 144 | // Testing product B002 145 | product = catalog.findProductByCode("B002"); 146 | 147 | assertTrue("11, testing method loadCatalog: " + product.toString(), product instanceof Jelly); 148 | 149 | Jelly productB002 = (Jelly) product; 150 | 151 | assertTrue("12, testing method loadCatalog: " + productB002.toString(), 152 | productB002.getCode().equals("B002") && productB002.getDescription().equals("solid,400ml")); 153 | 154 | } catch (Exception e) { 155 | fail("13, testing method loadCatalog: " + e.getMessage()); 156 | } 157 | } 158 | } -------------------------------------------------------------------------------- /exam4.1/catalog.dat: -------------------------------------------------------------------------------- 1 | PureMilk_A001_milk,400ml_10_2017-10-20_25 days_China_3.5%_2.9% 2 | PureMilk_A002_skim milk,800ml_18_2017-10-20_30 days_China_3.1%_3.9% 3 | Jelly_B001_solid,250ml_8.5_2017-10-20_15 days_solid_80% 4 | Jelly_B002_solid,400ml_14_2017-10-20_16 days_solid_85% 5 | Yogurt_C001_chocolate flavor,270ml_5_2017-10-20_40 days_chocolate 6 | Yogurt_C002_strawberry flavor,400ml_10_2017-10-20_40 days_strawberry 7 | MilkDrink_D001_taro flavor,250ml_13.1_2017-10-20_25 days_taro_2.9% 8 | MilkDrink_D002_apple flavor,400ml_16_2017-10-20_30 days_apple_3.8% -------------------------------------------------------------------------------- /exam4.1/classFiles/Catalog.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/Catalog.class -------------------------------------------------------------------------------- /exam4.1/classFiles/CatalogLoader.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/CatalogLoader.class -------------------------------------------------------------------------------- /exam4.1/classFiles/CurrentOrder.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/CurrentOrder.class -------------------------------------------------------------------------------- /exam4.1/classFiles/DataField.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/DataField.class -------------------------------------------------------------------------------- /exam4.1/classFiles/DataFormatException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/DataFormatException.class -------------------------------------------------------------------------------- /exam4.1/classFiles/FileCatalogLoader.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/FileCatalogLoader.class -------------------------------------------------------------------------------- /exam4.1/classFiles/HTMLSalesFormatter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/HTMLSalesFormatter.class -------------------------------------------------------------------------------- /exam4.1/classFiles/Jelly.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/Jelly.class -------------------------------------------------------------------------------- /exam4.1/classFiles/MilkDrink.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/MilkDrink.class -------------------------------------------------------------------------------- /exam4.1/classFiles/OrderItem.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/OrderItem.class -------------------------------------------------------------------------------- /exam4.1/classFiles/PlainTextSalesFormatter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/PlainTextSalesFormatter.class -------------------------------------------------------------------------------- /exam4.1/classFiles/Product.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/Product.class -------------------------------------------------------------------------------- /exam4.1/classFiles/PureMilk.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/PureMilk.class -------------------------------------------------------------------------------- /exam4.1/classFiles/Sale.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/Sale.class -------------------------------------------------------------------------------- /exam4.1/classFiles/SalesFormatter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/SalesFormatter.class -------------------------------------------------------------------------------- /exam4.1/classFiles/XMLSalesFormatter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/XMLSalesFormatter.class -------------------------------------------------------------------------------- /exam4.1/classFiles/XMLSalesFormatter.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | 3 | public class XMLSalesFormatter implements SalesFormatter { 4 | private static XMLSalesFormatter singletonInstance; 5 | 6 | public static XMLSalesFormatter getSingletonInstance() { 7 | if (singletonInstance == null) { 8 | singletonInstance = new XMLSalesFormatter(); 9 | } 10 | return singletonInstance; 11 | } 12 | 13 | public XMLSalesFormatter() { 14 | } 15 | 16 | public String formatSales(Sale sales) { 17 | String XML = new String("\n"); 18 | List orderList = sales.getOrderList(); 19 | for (CurrentOrder order : orderList) { 20 | XML = XML + " \n"; 21 | List items = order.getOrderItemList(); 22 | for (OrderItem item : items) { 23 | XML = XML + "\t quantity = \"" + item.getQuantity() 24 | + "\" price = \"" + item.getProduct().getPrice() 25 | + "\">" + item.getProduct().getCode() 26 | + "\n"; 27 | } 28 | XML = XML + " \n"; 29 | } 30 | XML = XML + ""; 31 | return XML; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /exam4.1/classFiles/Yogurt.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GroverZhu/LearnJava/6d0e4b21a2ee28363b9561eb4863ea6416879164/exam4.1/classFiles/Yogurt.class -------------------------------------------------------------------------------- /exam4.1/src/BrightFreshMilkGUI.java: -------------------------------------------------------------------------------- 1 | import java.awt.BorderLayout; 2 | import java.awt.GridLayout; 3 | import java.awt.event.ActionEvent; 4 | import java.awt.event.ActionListener; 5 | import java.io.BufferedWriter; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | import java.io.PrintWriter; 10 | import java.math.BigDecimal; 11 | import java.text.NumberFormat; 12 | import java.text.ParseException; 13 | import java.text.SimpleDateFormat; 14 | import java.util.ArrayList; 15 | 16 | import javax.swing.BorderFactory; 17 | import javax.swing.ButtonGroup; 18 | import javax.swing.JButton; 19 | import javax.swing.JFileChooser; 20 | import javax.swing.JFrame; 21 | import javax.swing.JLabel; 22 | import javax.swing.JList; 23 | import javax.swing.JPanel; 24 | import javax.swing.JRadioButton; 25 | import javax.swing.JScrollPane; 26 | import javax.swing.JTextArea; 27 | import javax.swing.JTextField; 28 | import javax.swing.ListSelectionModel; 29 | import javax.swing.event.ListSelectionEvent; 30 | import javax.swing.event.ListSelectionListener; 31 | 32 | /** 33 | * Bright Fresh Milk System. 34 | * 35 | */ 36 | public class BrightFreshMilkGUI extends JPanel { 37 | 38 | /* Standar error stream */ 39 | static private PrintWriter stdErr = new PrintWriter(System.err, true); 40 | 41 | /* Window width in pixels */ 42 | static private int WIDTH = 620; 43 | 44 | /* Window height in pixels */ 45 | static private int HEIGHT = 530; 46 | 47 | /* Size of the catalog list cell in pixels */ 48 | static private int CATALOG_CELL_SIZE = 50; 49 | 50 | /* Visible rows in catalog list */ 51 | static private int CATALOG_LIST_ROWS = 14; 52 | 53 | /* Size of the order list cell in pixels */ 54 | static private int ORDER_CELL_SIZE = 100; 55 | 56 | /* Visible rows in order list */ 57 | static private int ORDER_LIST_ROWS = 6; 58 | 59 | /* Size quantity text field */ 60 | static private int QUANTITY__TEXTFIELD_SIZE = 5; 61 | 62 | /* Size total text field */ 63 | static private int TOTAL__TEXTFIELD_SIZE = 8; 64 | 65 | /* Rows in status text area rows */ 66 | static private int STATUS_ROWS = 10; 67 | 68 | /* Rows in status text area cols */ 69 | static private int STATUS_COLS = 40; 70 | 71 | private JList catalogList; 72 | private JList orderList; 73 | private JButton addModifyButton; 74 | private JButton removeButton; 75 | private JButton registerSaleButton; 76 | private JButton displaySalesButton; 77 | private JButton saveSalesButton; 78 | private JPanel productPanel; 79 | private JLabel quantityLabel; 80 | private JLabel totalLabel; 81 | private JTextField quantityTextField; 82 | private JTextField totalTextField; 83 | private JTextArea statusTextArea; 84 | private JRadioButton plainRadioButton; 85 | private JRadioButton HTMLRadioButton; 86 | private JRadioButton XMLRadioButton; 87 | 88 | private JFileChooser fileChooser; 89 | 90 | private Catalog catalog; 91 | private CurrentOrder currentOrder; 92 | private Sale sales; 93 | private SalesFormatter salesFormatter; 94 | private NumberFormat dollarFormatter; 95 | 96 | /** 97 | * Loads a product catalog and starts the application. 98 | * 99 | * @param args 100 | * String arguments. Not used. 101 | * @throws IOException 102 | * if there are errors in the loading the catalog. 103 | */ 104 | public static void main(String[] args) throws IOException { 105 | 106 | String filename = ""; 107 | 108 | if (args.length != 1) { 109 | filename = "catalog.dat"; 110 | } else { 111 | filename = args[0]; 112 | } 113 | try { 114 | Catalog catalog = (new FileCatalogLoader()).loadCatalog(filename); 115 | 116 | JFrame frame = new JFrame("Bright Fresh Milk"); 117 | 118 | frame.setContentPane(new BrightFreshMilkGUI(catalog)); 119 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 120 | frame.setSize(WIDTH, HEIGHT); 121 | frame.setResizable(true); 122 | frame.setVisible(true); 123 | 124 | } catch (FileNotFoundException fnfe) { 125 | stdErr.println("The file does not exist"); 126 | 127 | System.exit(1); 128 | 129 | } catch (DataFormatException dfe) { 130 | stdErr.println("The file contains malformed data: " 131 | + dfe.getMessage()); 132 | 133 | System.exit(1); 134 | } catch (ParseException e) { 135 | stdErr.println(e.getMessage()); 136 | 137 | System.exit(1); 138 | } 139 | } 140 | 141 | /** 142 | * Instantiates the components and arranges them in a window. 143 | * 144 | * @param initialCatalog 145 | * a product catalog. 146 | */ 147 | public BrightFreshMilkGUI(Catalog initialCatalog) { 148 | 149 | // create the components 150 | catalogList = new JList(); 151 | orderList = new JList(); 152 | catalogList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 153 | catalogList.setVisibleRowCount(CATALOG_LIST_ROWS); 154 | catalogList.setFixedCellWidth(CATALOG_CELL_SIZE); 155 | orderList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 156 | orderList.setVisibleRowCount(ORDER_LIST_ROWS); 157 | orderList.setFixedCellWidth(ORDER_CELL_SIZE); 158 | addModifyButton = new JButton("Add|Modify Order Item"); 159 | removeButton = new JButton("Remove Order Item"); 160 | registerSaleButton = new JButton("Register Sale of Current Order"); 161 | displaySalesButton = new JButton("Display Sales"); 162 | saveSalesButton = new JButton("Save Sales"); 163 | quantityLabel = new JLabel("Quantity:"); 164 | totalLabel = new JLabel("Total:"); 165 | quantityTextField = new JTextField("", QUANTITY__TEXTFIELD_SIZE); 166 | totalTextField = new JTextField("$0.00", TOTAL__TEXTFIELD_SIZE); 167 | totalTextField.setEditable(false); 168 | statusTextArea = new JTextArea(STATUS_ROWS, STATUS_COLS); 169 | statusTextArea.setEditable(false); 170 | plainRadioButton = new JRadioButton("Plain", true); 171 | HTMLRadioButton = new JRadioButton("HTML"); 172 | XMLRadioButton = new JRadioButton("XML"); 173 | 174 | ButtonGroup group = new ButtonGroup(); 175 | 176 | group.add(plainRadioButton); 177 | group.add(HTMLRadioButton); 178 | group.add(XMLRadioButton); 179 | 180 | // Product Information panel 181 | productPanel = new JPanel(); 182 | productPanel.setBorder(BorderFactory 183 | .createTitledBorder( 184 | "Product Information")); 185 | 186 | 187 | 188 | 189 | // Catalog panel 190 | JPanel catalogPanel = new JPanel(); 191 | 192 | catalogPanel.setBorder(BorderFactory.createTitledBorder("Catalog")); 193 | catalogPanel.add(new JScrollPane(catalogList, 194 | JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 195 | JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)); 196 | 197 | // "Add|Modify Product" panel 198 | JPanel centralPanel = new JPanel(new BorderLayout()); 199 | JPanel addModifyPanel = new JPanel(new GridLayout(2, 1)); 200 | JPanel quantityPanel = new JPanel(); 201 | 202 | quantityPanel.add(quantityLabel); 203 | quantityPanel.add(quantityTextField); 204 | addModifyPanel.add(quantityPanel); 205 | addModifyPanel.add(addModifyButton); 206 | centralPanel.add(productPanel, BorderLayout.CENTER); 207 | centralPanel.add(addModifyPanel, BorderLayout.SOUTH); 208 | 209 | // Order panel 210 | JPanel orderPanel = new JPanel(new BorderLayout()); 211 | 212 | orderPanel.setBorder(BorderFactory.createTitledBorder("Order")); 213 | 214 | JPanel totalPanel = new JPanel(); 215 | 216 | totalPanel.add(totalLabel); 217 | totalPanel.add(totalTextField); 218 | 219 | JPanel buttonsPanel = new JPanel(new GridLayout(2, 1)); 220 | 221 | buttonsPanel.add(removeButton); 222 | buttonsPanel.add(registerSaleButton); 223 | orderPanel.add(totalPanel, BorderLayout.NORTH); 224 | orderPanel.add(new JScrollPane(orderList, 225 | JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 226 | JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER); 227 | orderPanel.add(buttonsPanel, BorderLayout.SOUTH); 228 | 229 | // Status panel 230 | JPanel bottomPanel = new JPanel(new BorderLayout()); 231 | 232 | bottomPanel.setBorder(BorderFactory.createTitledBorder("Status")); 233 | 234 | JPanel salesButtonsPanel = new JPanel(new GridLayout(1, 5)); 235 | 236 | salesButtonsPanel.add(plainRadioButton); 237 | salesButtonsPanel.add(HTMLRadioButton); 238 | salesButtonsPanel.add(XMLRadioButton); 239 | salesButtonsPanel.add(displaySalesButton); 240 | salesButtonsPanel.add(saveSalesButton); 241 | bottomPanel.add(new JScrollPane(statusTextArea, 242 | JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 243 | JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), 244 | BorderLayout.CENTER); 245 | bottomPanel.add(salesButtonsPanel, BorderLayout.SOUTH); 246 | 247 | // arrange panels in window 248 | setLayout(new BorderLayout()); 249 | add(catalogPanel, BorderLayout.WEST); 250 | add(centralPanel, BorderLayout.CENTER); 251 | add(orderPanel, BorderLayout.EAST); 252 | add(bottomPanel, BorderLayout.SOUTH); 253 | 254 | // start listening for list and buttons events 255 | catalogList.addListSelectionListener(new DisplayProductListener()); 256 | addModifyButton.addActionListener(new AddModifyListener()); 257 | removeButton.addActionListener(new RemoveListener()); 258 | registerSaleButton.addActionListener(new RegisterSaleListener()); 259 | displaySalesButton.addActionListener(new DisplaySalesListener()); 260 | saveSalesButton.addActionListener(new SaveSalesListener()); 261 | plainRadioButton.addActionListener(new PlainListener()); 262 | HTMLRadioButton.addActionListener(new HTMLListener()); 263 | XMLRadioButton.addActionListener(new XMLListener()); 264 | 265 | // populate the product catalog 266 | catalog = initialCatalog; 267 | String[] codes = new String[catalog.getProductList().size()]; 268 | int i = 0; 269 | for (Product product : catalog.getProductList()) { 270 | codes[i++] = product.getCode(); 271 | } 272 | catalogList.setListData(codes); 273 | 274 | currentOrder = new CurrentOrder(); 275 | currentOrder.setOrderItemList(new ArrayList()); 276 | currentOrder.setOrderTotal(new BigDecimal("0")); 277 | 278 | sales = new Sale(); 279 | sales.setOrderList(new ArrayList()); 280 | 281 | salesFormatter = PlainTextSalesFormatter.getSingletonInstance(); 282 | fileChooser = new JFileChooser(); 283 | dollarFormatter = NumberFormat.getCurrencyInstance(); 284 | } 285 | 286 | /* 287 | * Obtains a {@link JPanel} object with the information of a product. 288 | * 289 | * @param dataFields an {@link ArrayList} of {@link DataField} with the 290 | * product information. 291 | * 292 | * @return a {@link JPanel} with the product information. 293 | */ 294 | private JPanel getDataFieldsPanel(ArrayList dataFields) { 295 | 296 | JPanel panel = new JPanel(new BorderLayout()); 297 | JPanel centerPanel = new JPanel(new GridLayout(dataFields.size(), 1)); 298 | JPanel leftPanel = new JPanel(new GridLayout(dataFields.size(), 1)); 299 | 300 | panel.add(leftPanel, BorderLayout.WEST); 301 | panel.add(centerPanel, BorderLayout.CENTER); 302 | 303 | for (DataField field : dataFields) { 304 | 305 | JTextField valueTextField = new JTextField(field.getValue(), 17); 306 | 307 | valueTextField.setEditable(false); 308 | 309 | leftPanel.add(new JLabel(field.getName() + ":")); 310 | centerPanel.add(valueTextField); 311 | 312 | } 313 | 314 | return panel; 315 | } 316 | 317 | /** 318 | * This inner class handles list-selection events. 319 | */ 320 | class DisplayProductListener implements ListSelectionListener { 321 | 322 | /** 323 | * Displays the information of the selected product. 324 | * 325 | * @param event 326 | * the event object. 327 | */ 328 | public void valueChanged(ListSelectionEvent event) { 329 | 330 | if (!catalogList.getValueIsAdjusting()) { 331 | 332 | String code = (String) catalogList.getSelectedValue(); 333 | Product product = catalog.findProductByCode(code); 334 | 335 | productPanel.removeAll(); 336 | productPanel.setVisible(false); // Use this 337 | productPanel.add( // to update 338 | getDataFieldsPanel(getDataFields(product))); // the 339 | // panel 340 | productPanel.setVisible(true); // correctly 341 | 342 | statusTextArea.setText("Product " + code 343 | + " has been displayed"); 344 | } 345 | } 346 | 347 | private ArrayList getDataFields(Product product) { 348 | ArrayList result = new ArrayList(); 349 | result.add(new DataField("code", product.getCode())); 350 | result.add(new DataField("description", product.getDescription())); 351 | result.add(new DataField("price", dollarFormatter.format(product 352 | .getPrice()))); 353 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 354 | result.add(new DataField("productionDate", sdf.format(product 355 | .getProductionDate()))); 356 | result.add(new DataField("shelfLife", product.getShelfLife())); 357 | 358 | if (product instanceof MilkDrink) { 359 | MilkDrink milkDrink = (MilkDrink) product; 360 | result.add(new DataField("flavor", milkDrink.getFlavor())); 361 | result.add(new DataField("sugar", milkDrink.getSugar())); 362 | } else if (product instanceof Jelly) { 363 | Jelly jelly = (Jelly) product; 364 | result.add(new DataField("type", jelly.getType())); 365 | result.add(new DataField("diluteConcentration", jelly 366 | .getDiluteConcentration())); 367 | } else if (product instanceof PureMilk) { 368 | PureMilk pureMilk = (PureMilk) product; 369 | result.add(new DataField("countryOfOrigin", pureMilk 370 | .getCountryOfOrigin())); 371 | result.add(new DataField("butterfat", pureMilk.getButterfat())); 372 | result.add(new DataField("protein", pureMilk.getProtein())); 373 | } else if (product instanceof Yogurt) { 374 | Yogurt yogurt = (Yogurt) product; 375 | result.add(new DataField("flavor", yogurt.getFlavor())); 376 | } 377 | return result; 378 | } 379 | } 380 | 381 | /** 382 | * This inner class processes addModifyButton events. 383 | */ 384 | class AddModifyListener implements ActionListener { 385 | 386 | /** 387 | * Adds an order item to the current order. 388 | * 389 | * @param event 390 | * the event object. 391 | */ 392 | public void actionPerformed(ActionEvent event) { 393 | 394 | int quantity; 395 | String code = (String) catalogList.getSelectedValue(); 396 | 397 | try { 398 | quantity = Integer.parseInt(quantityTextField.getText()); 399 | } catch (NumberFormatException nfe) { 400 | statusTextArea.setText("Please enter an integer."); 401 | 402 | return; 403 | } 404 | if (quantity < 1) { 405 | statusTextArea.setText("Please enter a positive integer."); 406 | } else if (code == null) { 407 | statusTextArea 408 | .setText("Please select a product code from the catalog list."); 409 | } else { 410 | 411 | Product product = catalog.findProductByCode(code); 412 | 413 | OrderItem item = null; 414 | for (OrderItem orderItem : currentOrder.getOrderItemList()) { 415 | if (orderItem.getProduct().equals(product)) { 416 | item = orderItem; 417 | } 418 | } 419 | 420 | if (item == null) { 421 | item = new OrderItem(product, quantity); 422 | // add to currentOrder 423 | currentOrder.getOrderItemList().add(item); 424 | orderList.setListData(currentOrder.getOrderItemList() 425 | .toArray(new OrderItem[0])); 426 | statusTextArea.setText("The product has been added."); 427 | } else { 428 | item.setQuantity(quantity); 429 | orderList.setListData(currentOrder.getOrderItemList() 430 | .toArray(new OrderItem[0])); 431 | statusTextArea.setText("The product has been modified."); 432 | } 433 | 434 | // Calculate the orderTotal 435 | BigDecimal total = new BigDecimal("0"); 436 | for (OrderItem orderItem : currentOrder.getOrderItemList()) { 437 | total = total.add(orderItem.getProduct().getPrice() 438 | .multiply(new BigDecimal(orderItem.getQuantity()))); 439 | } 440 | currentOrder.setOrderTotal(total); 441 | totalTextField.setText(dollarFormatter.format(total)); 442 | quantityTextField.setText(""); 443 | } 444 | } 445 | } 446 | 447 | /** 448 | * This inner class processes removeButton events. 449 | */ 450 | class RemoveListener implements ActionListener { 451 | 452 | /** 453 | * Removes an order item from the current order. 454 | * 455 | * @param event 456 | * the event object. 457 | */ 458 | public void actionPerformed(ActionEvent event) { 459 | 460 | if (currentOrder.getOrderItemList().size() == 0) { 461 | statusTextArea.setText("The order is empty."); 462 | } else { 463 | 464 | OrderItem item = (OrderItem) orderList.getSelectedValue(); 465 | 466 | if (item == null) { 467 | statusTextArea 468 | .setText("Please select an item from the order list."); 469 | } else { 470 | currentOrder.getOrderItemList().remove(item); 471 | orderList.setListData(currentOrder.getOrderItemList() 472 | .toArray(new OrderItem[0])); 473 | 474 | // Calculate the orderTotal 475 | BigDecimal total = new BigDecimal("0"); 476 | for (OrderItem orderItem : currentOrder.getOrderItemList()) { 477 | total = total 478 | .add(orderItem 479 | .getProduct() 480 | .getPrice() 481 | .multiply( 482 | new BigDecimal(orderItem 483 | .getQuantity()))); 484 | } 485 | currentOrder.setOrderTotal(total); 486 | totalTextField.setText(dollarFormatter.format(total)); 487 | statusTextArea.setText("The product has been removed."); 488 | 489 | } 490 | } 491 | } 492 | } 493 | 494 | /** 495 | * This inner class processes registerSaleButton button events. 496 | */ 497 | class RegisterSaleListener implements ActionListener { 498 | 499 | /** 500 | * Registers the sale of the current order. 501 | * 502 | * @param event 503 | * the event object. 504 | */ 505 | public void actionPerformed(ActionEvent event) { 506 | 507 | if (currentOrder.getOrderItemList().size() == 0) { 508 | statusTextArea.setText("The order is empty."); 509 | } else { 510 | sales.getOrderList().add(currentOrder); 511 | currentOrder = new CurrentOrder(); 512 | currentOrder.setOrderItemList(new ArrayList()); 513 | currentOrder.setOrderTotal(new BigDecimal("0")); 514 | 515 | orderList.setListData(currentOrder.getOrderItemList().toArray( 516 | new OrderItem[0])); 517 | totalTextField.setText(dollarFormatter.format(0)); 518 | statusTextArea.setText("The sale has been registered."); 519 | } 520 | } 521 | } 522 | 523 | /** 524 | * This inner class processes displaySalesButtonevents. 525 | */ 526 | class DisplaySalesListener implements ActionListener { 527 | 528 | /** 529 | * Displays the sales information. 530 | * 531 | * @param event 532 | * the event object. 533 | */ 534 | public void actionPerformed(ActionEvent event) { 535 | /* PLACE YOUR CODE HERE */ 536 | // to do 537 | 538 | statusTextArea.setText(event.getActionCommand()); 539 | /***check.equals(plainRadioButton)*/ 540 | if (plainRadioButton.isSelected()) { 541 | salesFormatter = PlainTextSalesFormatter.getSingletonInstance(); 542 | statusTextArea.setText(salesFormatter.formatSales(sales)); 543 | } else if (HTMLRadioButton.isSelected()){ 544 | salesFormatter = HTMLSalesFormatter.getSingletonInstance(); 545 | statusTextArea.setText(salesFormatter.formatSales(sales)); 546 | } else if (XMLRadioButton.isSelected()){ 547 | salesFormatter = XMLSalesFormatter.getSingletonInstance(); 548 | statusTextArea.setText(salesFormatter.formatSales(sales)); 549 | } 550 | 551 | } 552 | } 553 | 554 | /* 555 | * This inner class processes saveSalesButton events. 556 | */ 557 | class SaveSalesListener implements ActionListener { 558 | 559 | /** 560 | * Saves the sales informations in a file. 561 | * 562 | * @param event 563 | * the event object. 564 | */ 565 | public void actionPerformed(ActionEvent event) { 566 | 567 | /* PLACE YOUR CODE HERE */ 568 | // to do 569 | if (sales.getOrderList().size() == 0) { 570 | statusTextArea.setText("No orders have been sold."); 571 | } else { 572 | int result = fileChooser.showOpenDialog(null); 573 | if (result == JFileChooser.APPROVE_OPTION){ 574 | String path = fileChooser.getSelectedFile().getAbsolutePath(); 575 | try { 576 | BufferedWriter fileWrite = new BufferedWriter(new FileWriter(path)); 577 | fileWrite.write(statusTextArea.getText()); 578 | fileWrite.close(); 579 | statusTextArea.setText("The sales information has been saved"); 580 | } catch (IOException e) { 581 | e.printStackTrace(); 582 | } 583 | } 584 | 585 | } 586 | 587 | } 588 | } 589 | 590 | /* 591 | * This inner class processes plainRadioButton events. 592 | */ 593 | class PlainListener implements ActionListener { 594 | 595 | /** 596 | * Sets the sales formatter to plain text. 597 | * 598 | * @param event 599 | * the event object. 600 | */ 601 | public void actionPerformed(ActionEvent event) { 602 | 603 | salesFormatter = PlainTextSalesFormatter.getSingletonInstance(); 604 | } 605 | } 606 | 607 | /* 608 | * This inner class processes HTMLRadioButton events. 609 | */ 610 | class HTMLListener implements ActionListener { 611 | 612 | /** 613 | * Sets the sales formatter to HTML. 614 | * 615 | * @param event 616 | * the event object. 617 | */ 618 | public void actionPerformed(ActionEvent event) { 619 | 620 | salesFormatter = HTMLSalesFormatter.getSingletonInstance(); 621 | } 622 | } 623 | 624 | /* 625 | * This inner class processes XMLRadioButton events. 626 | */ 627 | class XMLListener implements ActionListener { 628 | 629 | /** 630 | * Sets the sales formatter to XML. 631 | * 632 | * @param event 633 | * the event object. 634 | */ 635 | public void actionPerformed(ActionEvent event) { 636 | 637 | salesFormatter = XMLSalesFormatter.getSingletonInstance(); 638 | } 639 | } 640 | 641 | } --------------------------------------------------------------------------------