The program implements a simple order system with meal ordering, cancellation, and display functionality. It allows users to view meals on the menu, place orders for specific meals at tables, and cancel orders. The system maintains information about each meal including its name, vegetarian status, vegan status, and table orders.
Contribute Materials
Your contribution can guide someone’s learning journey. Share your
documents today.
4100COMP: Introduction to Programming Tutorial17: Coursework2- Design and Implementation Exercise Liverpool John Moores UniversityDepartment of Computer Science
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
4100COMP: Introduction to ProgrammingTutorial Solutions Introduction Up to the first coursework you have been writing Java programs that exist in a single class and just recently you have seen how Java’s strengths lie in the use of classes to build larger programs out of a series of individual classes, which at runtime create objectswhichcooperatewithoneanother.Forthissecondcourseworkyouare required to build a larger program, which consists of two or more classes, which will work together to provide an effective solution to a problem. In the last week you have been using classes in lab sessions, but this has largely been based on a precise description of how you should create the class and define its structure, as shown in the example below Writea class torepresent astudent accordingto thespecification below: Private members: int id – idnumber forthe student String name– name of the student String course – programme ofstudy int [] marks – anarrayof size 5 to store 5 marks (0-100) Public methods: Student(intid, Stringname,Stringcourse, int[] marks) –constructorwhichcreates a student accordingto the specifiedparameters int average() – calculates and returns the average mark forthe student, voidprint() – prints studentdetails Writea main program tocreate 3 studentobjects as: 1234Joe Bloggs,Computer Studies,{67, 55, 78,72, 50} 2341Sue White, Computer Science, {57, 85, 58,49, 61} 3412Ben Black, Software Engineering, {71, 45,66, 70, 51} For each studentprintthe detailsand calculate theaverage. For this tutorial we will walk through an example to show you how you can build a program, based on two classes from a realistic system description. The classes will not be quite as obvious as they were in the precise descriptions of the lab sessions, but we will show you how to follow a systematic process to determine the classes and then go on to develop a program based on these classes. You should apply these techniques when tackling coursework 2. Problem Specification The description below describes the system that we will develop in this tutorial. A restaurant requires an automatedmeal ordering system. The system isintended toprovide customers with atouchscreenat each table. Thetouchscreenwillprovide a main menu with3 options: - Displaymealsavailable - Order ameal - Cancela meal Liverpool John Moores UniversityDepartment of Computer Science
4100COMP: Introduction to ProgrammingTutorial Solutions - Quit The DisplayMealoptionwilldisplay a list ofmealsthat can beordered. Each mealis defined by: -An idnumber -A description of the meal -A vegetarianoption (setas true ifthe ingredients are vegetarian) -a vegan option (set as true ifthe ingredients are vegan) The Order aMealoptionwillallowa customer to order a meal byinputof their table number andthe meal number for thatparticularmeal.A particularmealcan have upto 10 orders (i.e. listof 10tablenumbers) The Cancela Mealoption willallowa customerto cancel ameal that was ordered previously. The Quit option will displaya goodbye messageand the touchscreen willhibernate. You are requiredto produce an application thatsimulate the MealOrdering Systemsby allowing auser to select thevarious menu options ofdisplayingmeals,ordering meals, cancellingordersand quitting. Onstartup yourapplicationwillneed to loada series of meals, which canbe used forthe simulation. The first step to developing the application is working out what classes we need and what shape and form these classes will take. These things will be considered in more detail in Problem Solving modules in semester 2, but for now we can perform a basic analysis by applying the “Nous and Verbs” approach to the system description. Step 1 We have repeated the system description text below and highlighted the main nouns and verbs in red and blue respectively. The idea is that the main Nouns will represent the “things” or classes that make up our system and the main verbs will represent the “operations” or methods that we need to include within the classes. Arestaurantrequiresanautomated meal orderingsystem. Thesystemis intendedtoprovide customerswithatouchscreenat eachtable. Thetouchscreenwillprovideamainmenuwith3 options: -Displaymealsavailable -Orderameal -Cancela meal -Quit The DisplayMealoptionwilldisplayalistof mealsthatcan be ordered. Each mealis definedby: -Anid number -Adescriptionof the meal -Avegetarianoption(setas true if the ingredients arevegetarian) -aveganoption(setas true if the ingredients arevegan) The Order aMealoptionwillallowa customertoordera mealbyinputof theirtable numberand themealnumberfor that particular meal. A particular meal canhaveup to10 orders (i.e.listof 10tablenumbers) The Cancela Mealoption willallowa customertocancel a mealthatwas ordered previously. The Quit option will displayagoodbye messageand the touchscreen willhibernate. Liverpool John Moores UniversityDepartment of Computer Science
4100COMP: Introduction to ProgrammingTutorial Solutions You are requiredtoproduceanapplicationthatsimulatethe Meal OrderingSystems by allowing ausertoselectthe variousmenuoptions of displaying meals, ordering meals, cancellingordersand quitting. Onstartup yourapplicationwillneed toloada series of meals, which canbe used forthe simulation. The process takes a bit of getting used to as there are lots of unnecessary nouns and verbs that we don’t actually need. For example we don’t actually need restaurant, or touchscreen, but we do need meal ordering system and meal. There is also a lot of repetition, so meal is repeated many times but we only need to consider one occurrence. After going through this process once or twice we can draw up an initial list which we can then refine to something like below. MainNouns ---------- 1. Restaurant 2. Automated MealOrdering System 3. Customer 4. Main menu 5. Meal 6. Vegetarian Option 7. Vegan Option 8. Table Number 9. List ofTableNumbers MainVerb Phrases ----------------- 1. Providea MainMenu 2. Displaya Listof Meals 3. Order aMeal 3. Cancel aMeal 4. Load a Seriesof Meals 5. Input aMeal Number 6. Input Table Number 7. Quit Step 2 Liverpool John Moores UniversityDepartment of Computer Science
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
4100COMP: Introduction to ProgrammingTutorial Solutions We can then refine this further to group things together, such that we can determine that the List of Meals is part of the Meal Ordering System, whereas Vegetarian Option and Vegan Option are part of Meal. So we can put this information together to produce a more structured view of the system, as below: Meal Ordering System -List of Meals Meal -Number -Description -Vegetarian Option -Vegan Option -List of Tables Now we have to think a bit further into the problem and note that the Display Meal Option mentions a List of Meals, which suggests that the Meal Ordering System should store some kind of collection. So we need to think of an appropriate data structure for this. We could use either a fixed sized array or a variable sized ArrayList. In this example we will use a fixed sized array. Now we have built up a good picture of the classes we need and thestructureof the classes (shown in red), so it’s time to think about thebehaviour(shown in blue). Meal Ordering System -List of Meals -Display List of Meals -Load a Series of Meals -Order Meal -Cancel Meal -Quit Meal -Number -Description -Vegetarian Option -Vegan Option -List of Tables -Order -Cancel Step 3 Liverpool John Moores UniversityDepartment of Computer Science
4100COMP: Introduction to ProgrammingTutorial Solutions Based on what we have so far we can put the information into a UML class diagram. UML will be covered in your second year of study, but for this coursework you are only required to produce a class diagram, as shown below, based on the information we have determined above. This can be done using a standard diagramming software like Visio (preferred), or just simply drawn using shapes in Powerpoint or Word. Note that for the Meal class we have added a methodtoStringto provide a string representation of a meal and its orders andgetMealNoto return the number for a meal. Also we don’t need a Quit method in theOrderingSystemclass. These are minor refinements from the lists we build up previously, which often occur as we build up a clearer picture of the system. OrderingSystem -meals:Meal[ ] +loadMeals():void +displayMeals():void Meal -no:int -desc:String -tables:int[ ] +toString():String +order(int tableNo):void 51-veggie:boolean -vegan:boolean +cancel(int tableNo) :boolean +getMealNo( ) :int +orderMeal( ) :void +cnacelMeal( ):void Step 4 We are now in a position to start writing the code. We can begin by doing a skeleton outline of the main classes, as shown below, which contains the member variables we determined previously. The skeleton outline also contains the definitions or stubs for the methods. package cw2_ex; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class OrderingSystem { private static Scannerinput= newScanner(System.in); private static final Meal[] meals =new Meal[5]; public static void main(String[] args) throws Exception { } private static void loadMeals() throws FileNotFoundException { Liverpool John Moores UniversityDepartment of Computer Science
4100COMP: Introduction to ProgrammingTutorial Solutions } private static void displayMeals(){ private static void orderMeal() { } private static void cancelMeal() { } } packagecw2_ex; publicclassMeal{ privateintno; privateStringdesc; privatebooleanveggie; privatebooleanvegan; privateint[]table; // constructors must doeverythingas setmethods arenot necessary here publicMeal(intno, Stringdesc,booleanveggie,booleanvegan,int[]table) { this.no=no; this.desc=desc; this.veggie=veggie; this.vegan=vegan; this.table=table; } publicStringtoString() { } publicvoidorder(inttableNo) { } publicbooleancancel(inttableNo) { } publicintgetMealNo() { } } Step 5 At this stage the solution is far from complete, but it’s important to realize that you would still get some marks for this as you have analysed the problem and provided an outline solution. However, with just a bit more effort you would achieve a better mark Liverpool John Moores UniversityDepartment of Computer Science
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
4100COMP: Introduction to ProgrammingTutorial Solutions by attempting to implement the methods, so let’s start by implementing the Meal class as below. packagecw2_ex; publicclassMeal{ privateintno; privateStringdesc; privatebooleanveggie; privatebooleanvegan; privateint[]table; // constructors must doeverythingas setmethods arenot necessary here publicMeal(intno, Stringdesc,booleanveggie,booleanvegan,int[]table) { this.no=no; this.desc=desc; this.veggie=veggie; this.vegan=vegan; this.table=table; } publicString toString() { Stringresult=no+" "+desc+" Vegetarian "+veggie+" Vegan "+vegan +" Table orders: "; for(inti=0;i<table.length;i++) { result+=" "+table[i]; } returnresult; } publicvoidorder(inttableNo) { for(inti=0;i<table.length;i++) { if(table[i] ==0) { table[i] =tableNo; return; } } } publicbooleancancel(inttableNo) { for(inti= 0;i<table.length;i++) { if(table[i] ==tableNo) { table[i] = 0; returntrue; } } returnfalse; } publicintgetMealNo() { returnthis.no; } } We’ve added the code for thetoStringmethod, which displays the meal data and then joins it with the elements of the array of table orders. We’ve added the code for orderandcancelwhich involves working through the array of table numbers and Liverpool John Moores UniversityDepartment of Computer Science
4100COMP: Introduction to ProgrammingTutorial Solutions setting the appropriate value. Notice thatcancelreturns a boolean value of true if we can cancel the order and false otherwise. Step 6 Next we can move on to implement theOrderingSystemclass. This requires a bit more work as we have to implement a menu (not a meal menu – a user selection menu) and load the meals data from a file, before we can move on to implement theorderMealandcancleMealmethods. If we develop this bit by bit we can first add the methodloadMealsto load the meals from file and implement the user selection menu as below. package cw2_ex; package cw2_ex; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class OrderingSystem { private static Scannerinput= newScanner(System.in); private static final Meal[] meals =new Meal[5]; public static void main(String[] args) throws Exception { loadMeals(); String choice = ""; do { System.out.println("\n-- MAINMENU--"); System.out.println("1 -Display Menu"); System.out.println("2 -OrderMeal"); System.out.println("3 -Cancel Meal"); System.out.println("Q -Quit"); System.out.print("Pick: "); choice = input.next().toUpperCase(); switch (choice) { case"1" :{ displayMeals(); break; } case"2" :{ orderMeal(); break; } case"3" :{ cancelMeal(); break; } Liverpool John Moores UniversityDepartment of Computer Science
4100COMP: Introduction to ProgrammingTutorial Solutions } } while (!choice.equals("Q")); System.out.println("--GOODBYE --"); } private static void loadMeals() throws FileNotFoundException { Scanner file = new Scanner(new FileReader("meals")); int index =0; while(file.hasNext()){ int no = Integer.parseInt(file.nextLine()); System.out.println(no); String desc= file.nextLine(); boolean veggie =Boolean.parseBoolean(file.nextLine()); boolean vegan = Boolean.parseBoolean(file.nextLine()); // read thelineof tables asa String and split intoints String tableData= file.nextLine(); String[] sTables= tableData.split(" "); int [] tables = new int[10]; for (int i=0; i<sTables.length; i++) { tables[i] =Integer.parseInt(sTables[i]); } meals[index] = new Meal(no, desc, veggie,vegan, tables); index++; } file.close(); } private static void displayMeals(){ } private static void orderMeal() { } private static void cancelMeal() { } } If we focus attention on theloadMealsmethod you can see that we have declared the Scanner to access the file as a local object within this method, as it doesn’t need to be accessed elsewhere in this program. We then have a familiar while loop similar to the one used for Coursework 1, which reads the lines from the file. Note that we have read the lines as Strings and useInteger.parseIntand Boolean.prarseBooleanto convert to int and boolean respectively. We also read the list of tables in as one String and then split this String into individual components, which we then convert into ints which we store in an array. The line to focus attention on in the while loop is: meals[index]= new Meal(no, desc,veggie,vegan,tables); Liverpool John Moores UniversityDepartment of Computer Science
Paraphrase This Document
Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
4100COMP: Introduction to ProgrammingTutorial Solutions This is a constructor call to create a series ofMealobjects. So we loop and read the data from the file and use it in a constructor call to createMealobjects. The result when this method finishes is that we have loaded into memory a series ofMeal objects that our program can use to perform order and cancel operations. Note that when the program finishes all the data will be lost, so we would normally arrange for the data to be saved when the program exits, which we will discuss later. (remember to close the file once you’ve finished with it). We’ve also added the user selection menu, which combines a do while loop with a switch case statement to allow the user to select an option. Note that each case block involves a call to a method to carry out the appropriate operation. The methods, like the data, inOrderSystemare declared as static, which is more convenient as they can be used class-wise (without creating an object) Step 7 We can now move on to implement thedisplayMeals,orderMealandcancelMeal methods package cw2_ex; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Scanner; public class OrderingSystem { private static Scannerinput= newScanner(System.in); private static final Meal[] meals =new Meal[5]; public static void main(String[] args) throws Exception { loadMeals(); String choice = ""; do { System.out.println("\n-- MAINMENU--"); System.out.println("1 -Display Menu"); System.out.println("2 -OrderMeal"); System.out.println("3 -Cancel Meal"); System.out.println("Q -Quit"); System.out.print("Pick: "); choice = input.next().toUpperCase(); switch (choice) { case"1" :{ displayMeals(); break; } Liverpool John Moores UniversityDepartment of Computer Science
4100COMP: Introduction to ProgrammingTutorial Solutions case"2" :{ orderMeal(); break; } case"3" :{ cancelMeal(); break; } } } while (!choice.equals("Q")); System.out.println("--GOODBYE --"); } private static void loadMeals() throws FileNotFoundException { Scanner file = new Scanner(new FileReader("meals")); int index =0; while(file.hasNext()){ int no = Integer.parseInt(file.nextLine()); System.out.println(no); String desc= file.nextLine(); boolean veggie =Boolean.parseBoolean(file.nextLine()); boolean vegan = Boolean.parseBoolean(file.nextLine()); // read thelineof tables asa String and split intoints String tableData= file.nextLine(); String[] sTables= tableData.split(" "); int [] tables = new int[10]; for (int i=0; i<sTables.length; i++) { tables[i] =Integer.parseInt(sTables[i]); } meals[index] = new Meal(no, desc, veggie,vegan, tables); index++; } file.close(); } private static void displayMeals(){ System.out.println("\n-- MEALS ON MENU --"); for (int i=0; i<meals.length;i++){ System.out.println(meals[i].toString()); } } private static void orderMeal() { displayMeals(); System.out.print("Entermealnumber: "); int mealNo= input.nextInt(); System.out.print("Entertablenumber: "); int tableNo= input.nextInt(); meals[mealNo-1].order(tableNo); } private static void cancelMeal() { System.out.println("\n-- CANCEL A MEAL --"); Liverpool John Moores UniversityDepartment of Computer Science
4100COMP: Introduction to ProgrammingTutorial Solutions System.out.print("Entermealnumber: "); int mealNo= input.nextInt(); System.out.print("Entertablenumber: "); int tableNo= input.nextInt(); boolean orderFound = false; for (int i=0; i<meals.length;i++){ if (meals[i].getMealNo() == mealNo){ if (meals[i].cancel(tableNo)){ orderFound= true; } } } if (!orderFound){ System.out.println("Nosuch meal orderedfor that table! "); } } } ThedisplayMealsmethod uses a for loop to loop over the meals and call the toStringmethod from theMealclass. TheorderMealmethod first calls the displayMealsmethod and then asks for meal and table numbers after which it goes on to call theordermethod from theMealclass. The cancelMeal method starts off similar to orderMeal, but then it needs to loop to find the meal involved before it calls cancelin theMealclass, Step 8 We could now test the program using some data, so we create a file based on our definition ofMealas below 1 Chicken Curry false false 0 0 00 0 00 0 00 2 FishFingers andChips false false 0 0 00 0 00 0 00 3 Lentil Stew true true 0 0 00 0 00 0 00 4 CheesePasta true false 0 0 00 0 00 0 00 5 Liverpool John Moores UniversityDepartment of Computer Science
Secure Best Marks with AI Grader
Need help grading? Try our AI Grader for instant feedback on your assignments.
4100COMP: Introduction to ProgrammingTutorial Solutions Steakand Chips false false 0 0 00 0 00 0 00 The following is the output received when the program is run with the data above -- MAIN MENU -- 1 - DisplayMenu 2 - Order Meal 3 - CancelMeal Q - Quit Pick: 2 -- MEALS ONMENU-- 1 Chicken Curry Vegetarian false Vegan false Table orders:0 0 00 0 00 0 00 2 Fish Fingers and Chips VegetarianfalseVeganfalseTableorders:00 0 00 0 00 0 0 3 Lentil Stew Vegetarian trueVegantrueTableorders:0 00 0 00 0 00 0 4 Cheese Pasta Vegetarian true Vegan false Table orders:00 0 00 0 00 0 0 5 Steak andChipsVegetarianfalseVeganfalseTableorders:0 00 0 00 0 00 0 Entermealnumber: 2 Entertablenumber:1 -- MAIN MENU -- 1 - DisplayMenu 2 - Order Meal 3 - CancelMeal Q - Quit Pick: As we mentioned previously, all the data is lost when the program exits. So for a program like this we would typically save the state on exit. This could be done via a saveDatamethod which we will leave up to you to implement as an exercise. The saveDatamethod would be called just before the program finishes (e.g. just before the GoodBye message). As a hint thesaveDatamethod would need to be compliant with theOrderSystemconstructor (which reads the data from file). For convenience thesaveDatamethod could call a method in theMealclass to write the details for each meal to file. Summary Through this exercise we have seen how to develop an application from a realistic specification. We have illustrated how we build up a picture of the classes we need to implement using nouns and verbs. We have also seen how we can create the classes bit by bit, from the skeleton outline to the finished solution. This example does not contain any validation, but you would be expected to include some validation, to achieve a top mark. Liverpool John Moores UniversityDepartment of Computer Science
4100COMP: Introduction to ProgrammingTutorial Solutions This example is actually harder than your coursework as there is a many to one relationship in that there can be many orders for one meal, whereas your coursework involves a one to one relationship in that there is one booking for each room. However, there is a fair amount of common ground between this example and your coursework, so it is a good idea to take time studying the example before you develop your coursework solution. It is crucial to stress that students who have understood the majority of what we have covered in the module will be able to fully complete work to this level (or students who have prior experience of programming). If you are still building your confidence with programming and still find some aspects challenging you should still attempt all that you can. We can award marks for any effort you make, but we cannot award marks for things you do not attempt. So the overall message is do what you can and ask for help and support from the staff teaching on the module. Liverpool John Moores UniversityDepartment of Computer Science