Microsoft Word - COMP1406-W23-T08.docxCOMP1406B/C/D–Winter2023–Tutorial#8 DueFriday,March17th,11:59pm1 COMP 1406 Winter XXXXXXXXXXTutorial #8 Objectives • To practice...

Please check if you can do through IDE Inteliji










Microsoft Word - COMP1406-W23-T08.docx COMP1406B/C/D–Winter2023–Tutorial#8 DueFriday,March17th,11:59pm 1 COMP 1406 Winter 2023 - Tutorial #8 Objectives • To practice handling Exceptions. • To create your own Exceptions. • To practice reading and writing binary, text, and object files Getting Started: Download the T08 - Base Code.zip file from Brightspace. This contains an IntelliJ project with the starting resources for this tutorial. The code provided in this tutorial contains the solutions from an earlier tutorial which involved a Game that we simulated with various movable and stationary objects such as Player, Ball, Trap, Wall and Prize. It also contains the completed code from a previous tutorial that involved Customer, Store and Mall classes. We will make use of these throughout this tutorial. COMP1406B/C/D–Winter2023–Tutorial#8 DueFriday,March17th,11:59pm 2 Tutorial Problems: 1) Recall these classes • GameObject • MovableObject • Player • Ball • StationaryObject • Wall • Trap • Prize • Game • GameTestProgram • GameBoard • GameBoardTestProgram Now we will add code that will generate a CollisionException when a Player collides with a wall. Of course, your code should attempt to prevent the Player from colliding with a wall, but in the off-chance that there is a bug in your code or that something unexpected occurs in the game, your player may end up colliding with the wall. A. Create and compile a CollisionException class as follows: public class CollisionException extends Exception { public CollisionException() { super("Player collided with wall !"); } } Note that any new exceptions that you define must extend the Exception class or one of its subclasses. Once this code is saved and compiled, you are able to generate such an exception. B. Copy this unfinished method code and then complete it in the Wall class: public boolean contains(Point2D p) { //return true if p.x is in the range from this.location.x to //(this.location.x+this.width-1) and if p.y is in the range from // this.location.y to (this.location.y+this.height-1) // otherwise return false } C. Add the following methods to the Game class so that we can get the Players and the Walls from the Game: COMP1406B/C/D–Winter2023–Tutorial#8 DueFriday,March17th,11:59pm 3 public ArrayList getPlayers() { ArrayList result = new ArrayList(); for (GameObject g: gameObjects) { if (g instanceof Player) result.add((Player)g); } return result; } public ArrayList getWalls() { ArrayList result = new ArrayList(); for (GameObject g: gameObjects) { if (g instanceof Wall) result.add((Wall)g); } return result; } D. Append the following piece of code to the end of the updateObjects() method in the Game class which will compare all players with all walls to see if a collision occurs and will then throw our newly defined exception if it has indeed occurred: ArrayList players = getPlayers(); ArrayList walls = getWalls(); for (Wall w: walls) { for (Player p: players) { if (w.contains(p.location)) throw new CollisionException(); } } The code will no longer compile. You should see an error stating: Unhandled exception: CollisionException. Java is telling us that we need to tell everyone that this updateObjects() method may now generate a CollisionException. E. Add an appropriate throws clause to the method definition as follows and then re- compile: public void updateObjects() throws CollisionException { ... } The GameTestProgram and GameBoardTestProgram will both generate the same compile error because we are calling the updateObjects() method from these classes and we now must decide what to do when the exception is generated. For now, we are not sure what to do and we just want to see if we can generate our exception. F. To simply satisfy the compiler for now, add throws CollisionException to the main methods as follows, and then re-compile: public static void main(String args[]) throws CollisionException { ... } COMP1406B/C/D–Winter2023–Tutorial#8 DueFriday,March17th,11:59pm 4 G. Run the GameTestProgram. You should see the exception generated as follows (although your code's line numbers may differ): Exception in thread "main" CollisionException: Player collided with wall ! at Game.updateObjects(Game.java:43) at GameTestProgram.main(GameTestProgram.java:53) ... at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) Congratulations, you have just thrown a brand-new exception. Notice that it occurs right where we threw it - from the updateObjects() method in the Game class. H. Run the GameBoardTestProgram. You should see the exception occur just before the Player collides with the wall above them: #################### # $ # # @ # # # # ########### # # ##### $ # # ^ # # # # # # # # # # @ # # O# # $ # # # #################### -------------------- Exception in thread "main" CollisionException: Player collided with wall ! at Game.updateObjects(Game.java:43) at GameBoardTestProgram.main(GameBoardTestProgram.java:40) ... at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) 2) Now we need to catch and handle our exception properly. First, let us catch it. But where do we catch it? Recall that we have added some throws clauses to our methods and eventually the main method threw the exception and the Java Virtual Machine caught it, and hence stopped the program. A. Change the following code from the main method in GameBoardTestProgram: for (int i=0; i<15; i++)="" {="" g.updateobjects();="" g.displayboard();="" system.out.println("--------------------");="" }="" into="" this:="" for="" (int="" i="0;"><15; i++) { try { g.displayboard(); comp1406b/c/d–winter2023–tutorial#8 duefriday,march17th,11:59pm 5 system.out.println("--------------------"); g.updateobjects(); } catch (collisionexception e) { // do nothing } } b. remove the throws collisionexception clause that we added from the main method's definition and then re-run the code. your program should run to completion because we caught the exception and ignored it. let's see how many times the exception actually occurred. c. add the following line inside the catch block, then re-run the code again: e.printstacktrace(); scroll through the program output. did you see how many times the exception occurred? i think you will notice it occurred 2 times, so the player hit 2 walls as it moved (because the player does not stop when it hits the walls, it goes right through them). obviously in a real game this would be a serious problem. for now, let us simply stop the player when it hits a wall. we do this by setting its speed to 0. d. so we need to add the following to the catch block instead of printing the stack trace: system.out.println("*** " + e.getmessage() + " ... setting speed to 0"); player.speed = 0; e. re-run the code. notice that the player no longer goes through the wall. you may also notice that the exception occurs a lot more now! what is going on? do you understand? print out the player's location from within the catch block. think about it. ask a ta if you do not understand why the exception occurs a lot now. 3) there are some bad things about the current code. first of all, we are catching the exception in the wrong spot. notice that our catch block "assumes" that it was the player object stored in the player variable that collided because it sets that player's speed to 0. however, if any other player collided with a wall, we would be setting the speed of the wrong player. can we fix this? yes. there are many ways to accomplish this. one interesting way is to allow the collisionexception to store the player that caused it. then we can access this from our catch block. looking to the future, we may wish to do something similar for ball objects and perhaps any movableobject. so let's allow any movableobject to be a cause of the exception. comp1406b/c/d–winter2023–tutorial#8 duefriday,march17th,11:59pm 6 a. add an attribute (i.e., instance variable) to the collisionexception class: movableobject source; then allow this to be set by the constructor by changing it as follows: public collisionexception(movableobject s) { super(s + " collided with wall !"); source = s; } b. go back to the updateobjects() method in the game class and pass in (to the call to the collisionexception constructor) the player who generated the exception. c. finally, in the catch block of the gameboardtestprogram, replace player with e.source. the code should compile and still run. it seems that we did not do much, but we did clean up the code and allow the exception to keep track of any movableobject that collides. 4) let's eliminate the problem that caused the exception to occur so many times. hopefully by now you realize that the exception kept occurring because the player was "stuck" on the wall. you will have to somehow "undo" the player's last forward movement. since we are already keeping track of the previouslocation of the player, we can simply restore it when a collision occurs. make the appropriate changes and then re-run your gameboardtestprogram to make sure that the exception occurs only once. the exception message should appear after the 6th board is displayed, not after the last displayed board as before. 5) we will now switch over to our customer/store example. run the storetestprogram to make sure that it works. also, create, save and compile the following test program: public class customertestprogram { public static void main(string args[]) { customer c1 = new customer("amie", 14, 100); customer c2 = new customer("brad", 15, 0); } } recall that we can create a dataoutputstream that allows us to output primitive types to a file as follows: dataoutputstream out = new dataoutputstream(new fileoutputstream("customer1.txt")); out.writeutf(c1.getname()); // utf is short for "unicode text format" out.writeint(c1.getage()); out.close(); comp1406b/c/d–winter2023–tutorial#8 duefriday,march17th,11:59pm 7 a. copy the above code to the customertestprogram so that the first customer amie is saved to a file called customer1.txt and add similar code so that brad is saved to a i++)="" {="" try="" {="" g.displayboard();="" comp="" 1406="" b/c/d="" –="" winter="" 2023="" –="" tutorial="" #8="" due="" friday,="" march="" 17th,="" 11:59pm="" 5="" system.out.println("--------------------");="" g.updateobjects();="" }="" catch="" (collisionexception="" e)="" {="" do="" nothing="" }="" }="" b.="" remove="" the="" throws="" collisionexception="" clause="" that="" we="" added="" from="" the="" main="" method's="" definition="" and="" then="" re-run="" the="" code.="" your="" program="" should="" run="" to="" completion="" because="" we="" caught="" the="" exception="" and="" ignored="" it.="" let's="" see="" how="" many="" times="" the="" exception="" actually="" occurred.="" c.="" add="" the="" following="" line="" inside="" the="" catch="" block,="" then="" re-run="" the="" code="" again:="" e.printstacktrace();="" scroll="" through="" the="" program="" output.="" did="" you="" see="" how="" many="" times="" the="" exception="" occurred?="" i="" think="" you="" will="" notice="" it="" occurred="" 2="" times,="" so="" the="" player="" hit="" 2="" walls="" as="" it="" moved="" (because="" the="" player="" does="" not="" stop="" when="" it="" hits="" the="" walls,="" it="" goes="" right="" through="" them).="" obviously="" in="" a="" real="" game="" this="" would="" be="" a="" serious="" problem.="" for="" now,="" let="" us="" simply="" stop="" the="" player="" when="" it="" hits="" a="" wall.="" we="" do="" this="" by="" setting="" its="" speed="" to="" 0.="" d.="" so="" we="" need="" to="" add="" the="" following="" to="" the="" catch="" block="" instead="" of="" printing="" the="" stack="" trace:="" system.out.println("***="" "="" +="" e.getmessage()="" +="" "="" ...="" setting="" speed="" to="" 0");="" player.speed="0;" e.="" re-run="" the="" code.="" notice="" that="" the="" player="" no="" longer="" goes="" through="" the="" wall.="" you="" may="" also="" notice="" that="" the="" exception="" occurs="" a="" lot="" more="" now!="" what="" is="" going="" on?="" do="" you="" understand?="" print="" out="" the="" player's="" location="" from="" within="" the="" catch="" block.="" think="" about="" it.="" ask="" a="" ta="" if="" you="" do="" not="" understand="" why="" the="" exception="" occurs="" a="" lot="" now.="" 3)="" there="" are="" some="" bad="" things="" about="" the="" current="" code.="" first="" of="" all,="" we="" are="" catching="" the="" exception="" in="" the="" wrong="" spot.="" notice="" that="" our="" catch="" block="" "assumes"="" that="" it="" was="" the="" player="" object="" stored="" in="" the="" player="" variable="" that="" collided="" because="" it="" sets="" that="" player's="" speed="" to="" 0.="" however,="" if="" any="" other="" player="" collided="" with="" a="" wall,="" we="" would="" be="" setting="" the="" speed="" of="" the="" wrong="" player.="" can="" we="" fix="" this?="" yes.="" there="" are="" many="" ways="" to="" accomplish="" this.="" one="" interesting="" way="" is="" to="" allow="" the="" collisionexception="" to="" store="" the="" player="" that="" caused="" it.="" then="" we="" can="" access="" this="" from="" our="" catch="" block.="" looking="" to="" the="" future,="" we="" may="" wish="" to="" do="" something="" similar="" for="" ball="" objects="" and="" perhaps="" any="" movableobject.="" so="" let's="" allow="" any="" movableobject="" to="" be="" a="" cause="" of="" the="" exception.="" comp="" 1406="" b/c/d="" –="" winter="" 2023="" –="" tutorial="" #8="" due="" friday,="" march="" 17th,="" 11:59pm="" 6="" a.="" add="" an="" attribute="" (i.e.,="" instance="" variable)="" to="" the="" collisionexception="" class:="" movableobject="" source;="" then="" allow="" this="" to="" be="" set="" by="" the="" constructor="" by="" changing="" it="" as="" follows:="" public="" collisionexception(movableobject="" s)="" {="" super(s="" +="" "="" collided="" with="" wall="" !");="" source="s;" }="" b.="" go="" back="" to="" the="" updateobjects()="" method="" in="" the="" game="" class="" and="" pass="" in="" (to="" the="" call="" to="" the="" collisionexception="" constructor)="" the="" player="" who="" generated="" the="" exception.="" c.="" finally,="" in="" the="" catch="" block="" of="" the="" gameboardtestprogram,="" replace="" player="" with="" e.source.="" the="" code="" should="" compile="" and="" still="" run.="" it="" seems="" that="" we="" did="" not="" do="" much,="" but="" we="" did="" clean="" up="" the="" code="" and="" allow="" the="" exception="" to="" keep="" track="" of="" any="" movableobject="" that="" collides.="" 4)="" let's="" eliminate="" the="" problem="" that="" caused="" the="" exception="" to="" occur="" so="" many="" times.="" hopefully="" by="" now="" you="" realize="" that="" the="" exception="" kept="" occurring="" because="" the="" player="" was="" "stuck"="" on="" the="" wall.="" you="" will="" have="" to="" somehow="" "undo"="" the="" player's="" last="" forward="" movement.="" since="" we="" are="" already="" keeping="" track="" of="" the="" previouslocation="" of="" the="" player,="" we="" can="" simply="" restore="" it="" when="" a="" collision="" occurs.="" make="" the="" appropriate="" changes="" and="" then="" re-run="" your="" gameboardtestprogram="" to="" make="" sure="" that="" the="" exception="" occurs="" only="" once.="" the="" exception="" message="" should="" appear="" after="" the="" 6th="" board="" is="" displayed,="" not="" after="" the="" last="" displayed="" board="" as="" before.="" 5)="" we="" will="" now="" switch="" over="" to="" our="" customer/store="" example.="" run="" the="" storetestprogram="" to="" make="" sure="" that="" it="" works.="" also,="" create,="" save="" and="" compile="" the="" following="" test="" program:="" public="" class="" customertestprogram="" {="" public="" static="" void="" main(string="" args[])="" {="" customer="" c1="new" customer("amie",="" 14,="" 100);="" customer="" c2="new" customer("brad",="" 15,="" 0);="" }="" }="" recall="" that="" we="" can="" create="" a="" dataoutputstream="" that="" allows="" us="" to="" output="" primitive="" types="" to="" a="" file="" as="" follows:="" dataoutputstream="" out="new" dataoutputstream(new="" fileoutputstream("customer1.txt"));="" out.writeutf(c1.getname());="" utf="" is="" short="" for="" "unicode="" text="" format"="" out.writeint(c1.getage());="" out.close();="" comp="" 1406="" b/c/d="" –="" winter="" 2023="" –="" tutorial="" #8="" due="" friday,="" march="" 17th,="" 11:59pm="" 7="" a.="" copy="" the="" above="" code="" to="" the="" customertestprogram="" so="" that="" the="" first="" customer="" amie="" is="" saved="" to="" a="" file="" called="" customer1.txt="" and="" add="" similar="" code="" so="" that="" brad="" is="" saved="" to="">
Mar 17, 2023
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here