Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Assignment - Adding Exceptions Gridwriter.zip - https://www.google.com/url?q=htt

ID: 3778238 • Letter: A

Question

Assignment - Adding Exceptions

Gridwriter.zip - https://www.google.com/url?q=http://fog.ccsf.edu/~jschatz/111B/GridWriter.zip&sa=D&ust=1480309408288000&usg=AFQjCNFhP7uJUyr980Zr-paJ0BbiHaBrqA

NumberGuessers.zip - https://www.google.com/url?q=http://fog.ccsf.edu/~jschatz/111B/NumberGuessers.zip&sa=D&ust=1480309408288000&usg=AFQjCNG8bgIrUuCdXOV3fnJGoq0NsBKG5g

For this assignment we will revisit assignments from previous modules and add exception handling. There are three classes that we have written that can be significantly improved by adding exceptions. The Circle class, for example, should probably throw an IllegalArgumentException if setRadius is invoked with a negative argument.

This week we will work on improving the GridWriter class and both of the NumberGuesser classes. You can download a simplified copy of the GridWriter code Here: GridWriter.zip. If you are not fully satisfied with your NumberGuesser and RandomNumberGuesser classes then you can download working code here: NumberGuessers.zip

Refresh your self on the details of these two projects, then read about the required modifications for the assignment below.

GridWriter Class: You will modify the GridWriter class by adding additional collection style functionality. The GridWriter class should get two new methods:

public int size() should return the number of GridItems stored in the GridWriter

public GridItem get(int index) should return the stored GridItems by index.

Consider the following code. The first line creates a GridWriter object. Then two items are added to the GridWriter. The index of the items will be 0, and 1. Notice how the for loop uses the size and get methods to print out the areas of the two items

GridWriter gw = new GridWriter(40, 50);

         

gw.add(new MyCircle(10, 10, 9));

gw.add(new MyRectangle(40, 0, 10, 10));

         

for (int i = 0; i < gw.size(); i++) {

        System.out.println(gw.get(i).getArea());

}        

Once you have these two methods working you should add exception logic to the get method. The following code should cause your GridWriter to thow an IndexOutOfBoundsException.

GridWriter gw = new GridWriter(40, 50);

         

gw.add(new MyCircle(10, 10, 9));

gw.add(new MyRectangle(40, 0, 10, 10));

GridItem i = gw.get(2);

Although the array inside the Gridwriter has a capacity of 4, it only stores two GridItems. ‘2’ is not a valid index. Add a throws statement to your get method that will thow an IndexOutOfBoundsException for any invalid index.

Submit your modified GridWriter.java.

NumberGuesser classes: When you worked on the NumberGuesser classes you might have noticed that the higer() and lower() methods can be called until there are no possible values left for the guesser to guess. In this case it seems fair for a NumberGuesser to throw an IllegalStateException.

If the NumberGuesser classes were upgraded in this matter then it would be possible to add some exception handling code to the number guessing game so that the users could be notified when the guesser has caught them cheating.

Add code to the higher and lower methods of both the NumberGuesser and RandomNumberGuesser class. Add a try-catch block to your number guessing game so that the user is notified if the sequence of ‘h’ and ‘l’ responses is untenable. Feel free to use the code in NumberGuessers.zip as the starting point for your modifications.

Explanation / Answer

GuessingGame.java

import java.util.*;

public class GuessingGame

{

       public static void main(String[] args)

       {

              NumberGuesser g = new NumberGuesser(1, 100);

              char response;

      

              do {

                     g.reset();

                     System.out.println("Think of a number from 1 to 100.");

                    

                     do {

                           response = promptUserAndGetResponse(g.getCurrentGuess());

                          

                           if (response == 'h') g.higher();

                           if (response == 'l') g.lower();

                          

                     } while (response != 'c');

                    

              } while (shouldPlayAgain());

       }

      

       /**

       * Helper Methods

       */

      

       public static char promptUserAndGetResponse(int guess) {

              char response;

              Scanner input = new Scanner(System.in);

             

              do {

                     try

                     {

                     System.out.print("Is it " + guess + "? (h/l/c): ");

                     response = input.next().charAt(0);

                     }

          catch(IllegalStateException e)

                {

                    System.out.println("Invalid input, You are cheating!!!");

                }

              } while (response != 'h' && response != 'l' && response != 'c');

             

              return response;

              }

      

      

       public static boolean shouldPlayAgain() {

              char response;

              Scanner input = new Scanner(System.in);

             

              do {

                     System.out.print("Do you want to play again? (y/n): ");

                     response = input.next().charAt(0);

              } while (response != 'y' && response != 'n');

             

              return response == 'y';

             

             

       }

}

NumberGuesser.java

package cheggg;

public class NumberGuesser {

      

       protected int high;

       protected int low;

      

       private int originalHigh;

       private int originalLow;

      

       public NumberGuesser(int l, int h) {

              low = originalLow = l;

              high = originalHigh = h;

       }

      

       public int getCurrentGuess() {

              return (high + low) / 2;

       }

      

       public void higher() throws IllegalStateException{

              low = getCurrentGuess() + 1;

       }

      

       public void lower() throws IllegalStateException {

              high = getCurrentGuess() - 1;

       }

      

       public void reset() {

              low = originalLow;

              high = originalHigh;

       }

}

RandomNumberGuesser.java

package cheggg;

import java.util.Random;

public class RandomNumberGuesser extends NumberGuesser {

      

       private int randomValue;

       private boolean randomValueNeedsUpdating;

       private Random generator;

      

       public RandomNumberGuesser(int l, int h) {

              super(l, h);

             

              randomValueNeedsUpdating = true;

              generator = new Random();

       }

      

       public int getCurrentGuess() {

             

              if (randomValueNeedsUpdating) {

                     randomValue = low + (generator.nextInt((high - low) + 1));

                     randomValueNeedsUpdating = false;

              }

             

              return randomValue;

       }

      

       public void higher()throws IllegalStateException {

              super.higher();

              randomValueNeedsUpdating = true;

       }

      

       public void lower() throws IllegalStateException{

              super.lower();

              randomValueNeedsUpdating = true;

       }

      

       public void reset() {

              super.reset();

              randomValueNeedsUpdating = true;

       }

      

}

GridWriter.java

public class GridWriter {

      

       private GridItem items[];

       private int size;

       private int rows;

       private int columns;

       private static final int INITIAL_CAPACITY = 4;

      

       public GridWriter(int r, int c) {

              items = new GridItem[INITIAL_CAPACITY];

              size = 0;

              rows = r;

              columns = c;

       }

       public void add(GridItem item) {

             

              // If the item array is full, we double its capacity

              if (size == items.length) {

                     doubleItemCapacity();

              }

             

              // Store the item GridItem in the items array

              items[size] = item;

              size++;

             

       }

       public int size()

       {

              // Copy by hand, so to speak

              for (int i = 0; i < items.length; i++) {

                     temp[i] = items[i];

                     System.out.print("the size is %d: " + i);

              }

       }

       public GridItem get(int index)

       {

              // If the item array is full, we double its capacity

                           if (index == items.length) {

                                  doubleItemCapacity();

                           }

                          

                           // Store the item GridItem in the items array

                           items[index] = items;

                           index++;

                           return index;

                     }

       }

              public void display() {

              int count;

             

              // Loop through all rows

              for (int r = rows; r >= 0; r--) {

                    

                     // Loop through all columns

                     for (int c = 0; c < columns; c++) {

                          

                           // Count the number of GridItems that cover this coordinate

                           count = 0;

                          

                           for (int i = 0; i < size; i++) {

                                  if (items[i].containsPoint(c, r)) {

                                         count++;

                                  }

                           }

                          

                           // Print the count in the coordinate location. Or a dot if the count is 0

                           if (count == 0) {         

                                  System.out.print(" .");

                           } else {

                                  System.out.print(" " + count);

                           }

                     }

                    

                     // New line at the end of each row

                     System.out.println();

              }

       }

      

       private void doubleItemCapacity() {

              // allocate a new array with double capacity

              GridItem temp[] = new GridItem[items.length * 2];

             

              // Copy by hand, so to speak

              for (int i = 0; i < items.length; i++) {

                     temp[i] = items[i];

              }

             

              // point the items array at the temp array.

              // The old array will be garbage collected

              items = temp;

              if (items >= INITIAL_CAPACITY)

               throw new IndexOutOfBoundsException(outOfBoundsMsg(INITIAL_CAPACITY]));

       }

       }

}

GridWriterProgram.java

public class GridWriterProgram {

    

     public static void main(String[] args) {

           GridWriter gw = new GridWriter(40, 50);

          

           gw.add(new MyCircle(10, 10, 9));

           gw.add(new MyCircle(25, 20, 12));

           gw.add(new MyCircle(25, 20, 5));

          

           gw.add(new MyRectangle(25, 25, 20, 15));

           gw.add(new MyRectangle(5, 5, 3, 4));

           gw.add(new MyRectangle(40, 0, 10, 10));

for (int i = 0; i < gw.size(); i++) {

        System.out.println(gw.get(i).getArea());

}       

           GridItem i = gw.get(2);

if (size >= 2)

               throw new IndexOutOfBoundsException(outOfBoundsMsg([2]));

       }

           gw.display();

     }

    

}

GridWriter.java

public class GridWriter {

      

       private GridItem items[];

       private int size;

       private int rows;

       private int columns;

       private static final int INITIAL_CAPACITY = 4;

       public GridWriter(int r, int c) {

              items = new GridItem[INITIAL_CAPACITY];

              size = 0;

              rows = r;

              columns = c;

       }

      

       public void add(GridItem item) {

             

              // If the item array is full, we double its capacity

              if (size == items.length) {

                     doubleItemCapacity();

              }

             

              // Store the item GridItem in the items array

              items[size] = item;

                            size++;

             

       }

       public int size()

       {

              // Copy by hand, so to speak

              for (int i = 0; i < items.length; i++) {

                     temp[i] = items[i];

                     System.out.print("the size is %d: " + i);

              }

       }

       public GridItem get(int index)

       {

              // If the item array is full, we double its capacity

                           if (index == items.length) {

                                  doubleItemCapacity();

                           }

                          

                           // Store the item GridItem in the items array

                           items[index] = item;

                    

                           index++;

                           return index;

                     }

       }

      

       public void display() {

              int count;

             

              // Loop through all rows

              for (int r = rows; r >= 0; r--) {

                    

                     // Loop through all columns

                     for (int c = 0; c < columns; c++) {

                          

                           // Count the number of GridItems that cover this coordinate

                           count = 0;

                          

                           for (int i = 0; i < size; i++) {

                                  if (items[i].containsPoint(c, r)) {

                                         count++;

                                  }

                           }

                          

      

       if (count == 0) {         

                                  System.out.print(" .");

                           } else {

                                  System.out.print(" " + count);

                           }

                     }

                    

                     // New line at the end of each row

                     System.out.println();

              }

       }

       private void doubleItemCapacity() {

              // allocate a new array with double capacity

              GridItem temp[] = new GridItem[items.length * 2];

             

              // Copy by hand, so to speak

              for (int i = 0; i < items.length; i++) {

                     temp[i] = items[i];

              }

             

              items = temp;

       }

       }

}

MyCircle.java

public class MyCircle extends GridItem {

     private int radius;

    

     public MyCircle(int xValue, int yValue, int r) {

           x = xValue;

           y = yValue;

           radius = r;

     }

    

     public double getArea() {

           return Math.PI * Math.pow(radius, 2);

     }

    

     public boolean containsPoint(int xValue, int yValue) {

           double dx = x - xValue;

           double dy = y - yValue;

           double distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));

          

           return distance <= radius;

if (radius <=0)

               throw new IllegalArgumentException(outOfBoundsMsg([radius]));

       }

     }

}