Question

IN JAVA: Write a class, ZeroException, which is an Exception, and is used to signal that somethi...

IN JAVA:

  1. Write a class, ZeroException, which is an Exception, and is used to signal that something is zero when it shouldn't be.
  2. Write the class ArrayManipulator which creates an array and provides several methods to manipulate values taken from an array.

ZeroException Task:

Exceptions are used to signal many types of problems in a program. We can write our own as well to describe specific exceptional conditions which may arise. The advantage of doing so is that when exceptions are thrown, we can use the type of the exception we've created to identify the problem from among a set of other possible problems.

Here we have invented the notion of a "zero exception," which we would use to indicate that something has a zero value when it shouldn't. So in our main task below, we have a class which can return values but is not allowed to return a zero (for whatever arbitrary reason). Thus, whenever it is supposed to return a value, and the value happens to be zero, it will throw a ZeroExceptioninstead. Do not confuse this with a divide by zero error. This class will be fairly simple: the only constructor we will expect to be able to call is a default constructor (truly, we hardly need to put anything in the class for it to work - an exception's job is only to report that an error happened, so it really only needs to exist to do its work).

ArrayManipulator Task:

(7pts) Now we write a simple class which stores an array and allows us to set or get elements of the array. The getters include methods which manipulate values before returning them (i.e. multiply the number by a constant or divide the number by a constant). We will add one more constraint: the getters must never return a zero value. Instead, whenever we have a zero value, we would throw a zero exception instead.

The class should implement the following public methods:

  • public ArrayManipulator(int size) Initialize an internal array of integers using the given size.
  • public void set(int i, int v) A setter which sets the value at index i of the array to v.
  • public int get(int i) A getter which gets the value at index i of the array. However, if the value would be zero, it should throw a ZeroException instead.
  • public int getMult(int i, int m) A getter which gets the value at index i of the array and returns the product of that value and m. It should not change the value in the array, just return the result. However, if the result would be zero, it should throw a ZeroException instead.
  • public int getDiv(int i, int d) A getter which gets the value at index i of the array and returns that value divided by d. It should not change the value in the array, just return the result. However, if the result would be zero, it should throw a ZeroException instead.
  • public void print(int mode, int i, int v) This method will call either get(), getMult(), or getDiv(), depending on the mode parameter which is passed in, and print the result. If mode==0 then it calls get(), if mode==1 then it calls getMult(), and if mode==2 then it calls getDiv(). For any other value of mode, it will do nothing. It will make the call using i as the index and (if necessary) v as the value. If the result of the call is a division by zero, then print "divide by zero" instead. If the result is an out-of-bounds array access, then "out of bounds" should be printed. Finally, if the result of the operation is an illegal zero, then "zero results" should be printed.

Test Cases:

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
import java.io.*;

public class E9tester {
  public static void main(String args[]){
    org.junit.runner.JUnitCore.main("E9tester");
  }
  
  @Test public void zeroexception_exists() {
    Exception e = new ZeroException();
  }

  @Test public void arraymanipulator_getset() throws Exception {
    ArrayManipulator a = new ArrayManipulator(5);
    for (int i = 0;  i < 5;  i++) a.set(i, i+1);
    for (int i = 0;  i < 5;  i++) {
      String errMsg = String.format("incorrect value at position %d", i);
      assertEquals(errMsg, (i+1), a.get(i));
    }
    
  }
  
  private int[][] multRes = { 
    {1,2,3,4,5}, {2,4,6,8,10}, {3,6,9,12,15}, {4,8,12,16,20}, {5,10,15,20,25} 
  };
  @Test public void arraymanipulator_getmult() throws Exception {
    ArrayManipulator a = new ArrayManipulator(5);
    for (int i = 0;  i < 5;  i++) a.set(i, i+1);
    for (int[] testCase : multRes) {
       int m = testCase[0];
       for (int i = 0;  i < 5;  i++) {
         String errMsg = String.format("incorrect value at position %d when multiplying %d by %d", i, i+1, m);
         assertEquals(errMsg, testCase[i], a.getMult(i, m));
       }
       for (int i = 0;  i < 5;  i++) {
         String errMsg = String.format("incorrect value at position %d when multiplying %d by %d (repeated)", i, i+1, m);
         assertEquals(errMsg, testCase[i], a.getMult(i, m));
       }
    }
  }
  
  private int[][] divRes = { 
    {5,10,15,20,25,1}, {2,5,7,10,12,2}, {1,3,5,6,8,3}, {1,2,3,5,6,4}, {1,2,3,4,5,5} 
  };
  @Test public void arraymanipulator_getdiv() throws Exception {
    ArrayManipulator a = new ArrayManipulator(5);
    for (int i = 0;  i < 5;  i++) a.set(i, 5*i+5);
    for (int[] testCase : divRes) {
       int d = testCase[5];
       for (int i = 0;  i < 5;  i++) {
         String errMsg = String.format("incorrect value at position %d when dividing %d by %d", i, (5*i+5), d);
         assertEquals(errMsg, testCase[i], a.getDiv(i, d));
       }
       for (int i = 0;  i < 5;  i++) {
         String errMsg = String.format("incorrect value at position %d when dividing %d by %d (repeated)", i, (5*i+5), d);
         assertEquals(errMsg, testCase[i], a.getDiv(i, d));
       }
    }
  }
  
  @Test public void arraymanipulator_print() throws Exception {
    ArrayManipulator a = new ArrayManipulator(5);
    for (int i = 0;  i < 5;  i++) a.set(i, i+1);
    setCapture();
    for (int m = 0; m < 5; m++) {
      for (int i = 0;  i < 5;  i++) a.print(m,i,2);
    }
    a.print(0,10,0);
    a.print(1,10,0);
    a.print(2,10,0);
    a.print(0,0,0);
    a.print(1,0,0);
    a.print(2,0,0);
    a.set(0,0);
    a.print(0,0,0);
    
    String expected = "1\n2\n3\n4\n5\n"+
         "2\n4\n6\n8\n10\n"+
         "zero result\n1\n1\n2\n2\n"+
         "out of bounds\nout of bounds\nout of bounds\n" +
         "1\nzero result\ndivide by zero\n" +
         "zero result\n";
         
    String actual = getCapture();
        assertEquals(expected, actual);
    unsetCapture();
    
  }
  
  /** the lines below are for setting up input/output redirection so that the
    * tests can see what is being set to the screen as well as produce its own
    * pseudo-keyboard input.  No test appear below here. */
  
  static ByteArrayOutputStream localOut, localErr;
  static PrintStream sOut, sErr;

  @BeforeClass public static void setup() throws Exception {
    sOut = System.out;
    sErr = System.err;
  }
  
  @AfterClass public static void cleanup() throws Exception {
    unsetCapture();
  }
  
  private static void setCapture() {
   localOut = new ByteArrayOutputStream();
   localErr = new ByteArrayOutputStream();
   System.setOut(new PrintStream( localOut ) );
   System.setErr(new PrintStream( localErr ) );
  }

  private static String getCapture() {
   return localOut.toString().replaceAll("\\r?\\n", "\n");
  }

  private static void unsetCapture() {
   System.setOut( null );
   System.setOut( sOut );
   System.setErr( null );
   System.setErr( sErr );
  }

}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

ZeroException.java:

public class ZeroException extends Exception{
    public ZeroException(){
        super();
    }

    public ZeroException(String message){
        super(message);
    }
}

---------------------------------------------------------------------------------------

ArrayManipulator.java:

public class ArrayManipulator{

    private int array[];

    public ArrayManipulator(int size){
        array = new int[size];
    }

    public int get(int i) throws ZeroException{
        if(array[i] == 0){
            throw new ZeroException("zero exception");
        }
        return array[i];
    }

    public void set(int i, int v) throws ZeroException{
        if(v == 0){
            throw new ZeroException("zero exception");
        }
        array[i] = v;
    }

    public int getMult(int i, int m) throws ZeroException{
        int result = array[i] * m;
        if(result == 0){
            throw new ZeroException("zero exception");
        }
        return result;
    }

    public int getDiv(int i, int d) throws ZeroException{
        int result = array[i] / d;
        if(result == 0){
            throw new ZeroException("zero exception");
        }
        return result;
    }

    public void print(int mode, int i, int v){
        try {
            switch (mode) {
                case 0:
                    get(i);
                    break;
                case 1:
                    getMult(i, v);
                    break;
                case 2:
                    getDiv(i, v);
                    break;
            }
        }
        catch(ArithmeticException ex){
            System.out.println("Divide by zero");
        }
        catch(ArrayIndexOutOfBoundsException ex){
            System.out.println("out of bounds");
        }
        catch(ZeroException ex){
            ex.getMessage();
        }
    }
}
Add a comment
Know the answer?
Add Answer to:
IN JAVA: Write a class, ZeroException, which is an Exception, and is used to signal that somethi...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please use Java only. Write a class, ZeroException, which is an Exception, and is used to signal...

    Please use Java only. Write a class, ZeroException, which is an Exception, and is used to signal that something is zero when it shouldn't be. -- Not needed Write the class ArrayManipulator which creates an array and provides several methods to manipulate values taken from an array. --needed ZeroException Task: -- Not needed Exceptions are used to signal many types of problems in a program. We can write our own as well to describe specific exceptional conditions which may arise....

  • Write a unit test to test the following class. Using Java : //Test only the debit...

    Write a unit test to test the following class. Using Java : //Test only the debit method in the BankAccount. : import java.util.*; public class BankAccount { private String customerName; private double balance; private boolean frozen = false; private BankAccount() { } public BankAccount(String Name, double balance) { customerName = Name; this.balance = balance; } public String getCustomerName() { return customerName; } public double getBalance() { return balance; } public void setDebit(double amount) throws Exception { if (frozen) { throw...

  • This is Crypto Manager blank public class CryptoManager { private static final char LOWER_BOUND = '...

    This is Crypto Manager blank public class CryptoManager { private static final char LOWER_BOUND = ' '; private static final char UPPER_BOUND = '_'; private static final int RANGE = UPPER_BOUND - LOWER_BOUND + 1; /** * This method determines if a string is within the allowable bounds of ASCII codes * according to the LOWER_BOUND and UPPER_BOUND characters * @param plainText a string to be encrypted, if it is within the allowable bounds * @return true if all characters...

  • JAVA PROBLEMS 1. Update the below method to throw an IndexOutOfBoundsException: public E get(int index) {...

    JAVA PROBLEMS 1. Update the below method to throw an IndexOutOfBoundsException: public E get(int index) {         if (index < 0 || index > numItems) {             System.out.println("Get error: Index "                         + index + " is out of bounds.");             return null;         }         return array[index]; } Hint: Update both the method signature and the method body! 2. Update the below method to include a try-catch block rather than throwing the exception to...

  • This wont take you more than 15 mins. Comple the two method and besure to test...

    This wont take you more than 15 mins. Comple the two method and besure to test with Junit test that provided below. toArray() -- this method returns a newly allocated array containing the elements in the multiset. The array this method returns must only contain the elements in the multiset and not any nulls or other values that are stored in the backing store, but are not in the multiset. fromArray(E[] arr) -- this method updates the multiset so that...

  • need java code for this question Question 2 (15 marks) (a) Does the following class successfully...

    need java code for this question Question 2 (15 marks) (a) Does the following class successfully compile? Explain your answer. public class MyClass public static void main(String arge) if(Integer.parseInt(args[0]) < 0) throw new RuntimeException(); C { 1 } If the class does compile, describe what will happen when we run it with command: java MyClass -10 (5 marks) (b) Write a complete definition of the method with the heading given below: public static double calculate insurance Premium double carValue, int...

  • Can someone please explain this piece of java code line by line as to what they...

    Can someone please explain this piece of java code line by line as to what they are doing and the purpose of each line (you can put it in the code comments). Code: import java.util.*; public class Array { private Integer[] array; // NOTE: Integer is an Object. Array() {     super();     array = new Integer[0]; } Array(Array other) {     super();     array = other.array.clone(); // NOTE: All arrays can be cloned. } void add(int value) {    ...

  • Need help with writing a Client test in JAVA

    public class TutorialSpace {                  // slots — the number of available slots in a tutorial class         private int slots;         // activated — true if the tutorial class has been activated         private boolean activated;                  /**         * TutorialSpace(n) — a constructor for a tutorial class with n slots.         *          * @param n         */         public TutorialSpace(int n) {                 this.slots = n;                 this.activated = false;         }                  /**         * activate() — activates the tutorial class. Throws an exception if the         * tutorial class has already been activated.         *          * @throws NotActivatedException         */                  public void activate() throws NotActivatedException {                 if (activated) {                         throw new NotActivatedException("Already Activated");                 } else {                         activated = true;                 }         }                  /**         * reserveSlot()—enrol a student into the tutorial class by decreasing the         * number of slots left for enrolling in the class. Throws an exception if slot         * is either completely used or the tutorial class is not active.         *          * @throws EmptyException         */         public void reserveSlot() throws EmptyException {                                  if (!activated || slots == 0) {                         throw new EmptyException("Tutorial space is empty");                 } else {                         slots--;                 }         }                  /**         * slotsRemaining()—returns the number of slots remaining in the tutorial class.         */                  public int slotsRemaining() {                 return slots;         }          } public class NotActivatedException extends Exception {                  /**         *          */         private static final long serialVersionUID = 1L;                  public NotActivatedException(String msg) {                 super(msg);         }          } public class EmptyException extends Exception {                  /**         *          */         private static final long serialVersionUID = 1L;         public EmptyException(String msg) {                 super(msg);         }                  ...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • 2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority...

    2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority queue using bottom-up algorithm. The expected run time should be O(n), where n is the total number of data. BubbleDown method is provided. You may test it in this minHeap public class MinHeapPriorityQueue<E extends Comparable<? super E>>{ private E data[]; private int size; public MinHeapPriorityQueue(){ this(100); } public MinHeapPriorityQueue(int cap){ size = 0; data = (E[]) new Comparable[cap]; } public MinHeapPriorityQueue(int[] a){ } public...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT