Introduction
In this lab we will look at the information given by thrown exceptions. In particular, we will see that a given design does not give the most useful information that it could. We will explore how to fix it.
The Program
We have three classes in the project. StringArray is similar to the class in the homework, with much functionality removed. Names is meant to be a collection of names that has a StringArray used to store them. It has a method used to check if a given name is stored at a certain index. Finally, Driver tries adding some names to a Names object and then tests if a certain name exists at various indices.
The Problem
When you run your driver, you don’t get the most useful information. The console just informs you that something broke. This is not very specific or informative. Your task is to investigate why the information given is so poor, and fix the problem.
To Get Credit
Bare minimum: Write a correct written explanation of the problem with the design. How is this program failing to use exceptions in the most useful way? Describe how it could be fixed.
Good: Fix the problem in the code. When the Driver runs, different errors should give different, useful output.
Excellent: Change the program so that it crashes after printing out the error message. When it crashes, make sure the stack trace takes you all the way to the original source of the crash.
public class Driver {
static String[] array = new String[] {"Inez","Jayne","Malikah","Tymoteusz","Lilli","Israr",null,"Christos", "Misaki"};
public static void main(String args[]){
Names names = new Names(array);
for(int i=0; i<10; i++) {
try {
boolean result = names.containsAt("Malikah", i);
System.out.println("Index " + i + " contains \'should\'? " + result);
}
catch (RuntimeException ex) {
System.out.println("Index " + i + " contains \'should\'? " + ex.getMessage());
}
}
}
}
public class Names {
private StringArray nameArr;
public Names(String[] names) {
nameArr = new StringArray(names);
}
/**
* Check if the string stored at index is the same as the given string
* @param string to compare to
* @param index to look at
* @throws RuntimeException if something breaks
* @return whether the string at the index is the same as the given string
*/
public boolean containsAt(String string, int index) {
try {
return(nameArr.retrieveStringAt(index).contentEquals(string));
}
catch(IllegalArgumentException | NullPointerException ex) {
throw new RuntimeException("something broke");
}
}
}
/*
* A class that stores a number of Strings in an array.
* It provides a number of methods to interact with the Strings.
* Null references are allowed in the String array
*/
public class StringArray {
private String arr[];
/**
* Constructor for the SuperStringArray class
* @param arr the string array to store in this object
*/
public StringArray(String[] arr) {
this.arr = arr;
}
@Override
public String toString(){
return arr.length + " String(s)";
}
public String retrieveStringAt(int stringIndex){
if (stringIndex < 0 || stringIndex >= arr.length)
throw new IllegalArgumentException("the index " + stringIndex + " is out of bounds");
return arr[stringIndex];
}
}
Please rate the answer and do comment in case of any query.
Thanks.
Program flow:
retrieveStringAt() method throws IllegalArgumentException if index is out of bounds. This exception is caught in containsAt() method of ‘Names’ class, but instead of throwing the exception which it received, a new RunTimeException is being created with a custom message – “something broke”. So the actual reason for exception is not being displayed.
Similarly, when a NullPointerException is thrown, containsAt() method of 'Names' class throws the same custom error message - "something broke" instead of the actual error message.
Fix/Solution:
Instead of returning the custom message by throwing the RunTimeException, throwing the actual error message (ex) can fix and display the same instead of “something broke”.
["throw new RuntimeException("something broke");" has been modified to "throw ex;"]
Note: There is no change in StringArray.java file
The modified classes are shown below:
Names.java:
public class Names {
private StringArray nameArr;
public Names(String[] names) {
nameArr = new StringArray(names);
}
/**
* Check if the string stored at index is the same as the given
string
* @param string to compare to
* @param index to look at
* @throws RuntimeException if something breaks
* @return whether the string at the index is the same as the given
string
*/
public boolean containsAt(String string, int index) {
try {
return(nameArr.retrieveStringAt(index).contentEquals(string));
}
catch(IllegalArgumentException | NullPointerException ex) {
throw ex;
}
}
}
Driver.java:
public class Driver {
static String[] array = new String[]
{"Inez","Jayne","Malikah","Tymoteusz","Lilli","Israr",null,"Christos",
"Misaki"};
public static void main(String args[]){
Names names = new Names(array);
for(int i=0; i<10; i++) {
try {
boolean result = names.containsAt("Malikah", i);
System.out.println("Index " + i + " contains \'Malikah\'? " +
result);
}
catch (Exception ex) {
System.out.print("Index " + i + " contains \'Malikah\'? ");
ex.printStackTrace();
}
}
}
}
Screenshot of the modified code is shown below:
Names.java:


Screenshot of sample output is shown below:

************************************** Crashing the program after printing error message **************************************
Removing the exception handling (try-catch) mechanism in
Driver.java crashes the program after printing the error
message.
Note: There is no change in StringArray.java file
Code:
Names.java:
public class Names {
private StringArray nameArr;
public Names(String[] names) {
nameArr = new StringArray(names);
}
/**
* Check if the string stored at index is the same as the given
string
* @param string to compare to
* @param index to look at
* @throws RuntimeException if something breaks
* @return whether the string at the index is the same as the given
string
*/
public boolean containsAt(String string, int index) {
try {
return(nameArr.retrieveStringAt(index).contentEquals(string));
}
catch(IllegalArgumentException | NullPointerException ex) {
throw ex;
}
}
}
Driver.java:
public class Driver {
static String[] array = new String[]
{"Inez","Jayne","Malikah","Tymoteusz","Lilli","Israr",null,"Christos",
"Misaki"};
public static void main(String args[]){
Names names = new Names(array);
for(int i=0; i<10; i++) {
boolean result = names.containsAt("Malikah", i);
System.out.println("Index " + i + " contains \'Malikah\'? " +
result);
}
}
}
Screenshots:
Names.java:

Driver.java:

Sample output:

Hope this helps you and would suffice your requirement.
Introduction In this lab we will look at the information given by thrown exceptions. In particular,...
must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int [] arr); public static void quickSort(int [] arr); public static void mergeSort(int [] arr); The quick sort and merge sort must be implemented by using recursive thinking. So the students may provide the following private static methods: //merge method //merge two sorted portions of given array arr, namely, from start to middle //and from middle + 1 to end into one sorted portion, namely,...
Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong here is what i was told that was needed. Ill provide my code at the very end. Here is what is missing : Here is my code: public class GSL { private String arr[]; private int size; public GSL() { arr = new String[10]; size = 0; } public int size() { return size; } public void add(String value) { ...
Given is the implementation of the class IntegeArray what we did for Assignment 5. This implementation has only one data member or attribute private int[] arr; If the length of the array is also added as an attribute or data member of the class as shown below, please rewrite the whole IntegerArray class implementation to reflect this new added data member of len. Complete the code given below (and submit based on the given code). No main needs to be...
Problem Definition: Problem: Given an array of integers find all pairs of integers, a and b, where a – b is equal to a given number. For example, consider the following array and suppose we want to find all pairs of integers a and b where a – b = 3 A = [10, 4, 6, 16, 1, 6, 12, 13] Then your method should return the following pairs: 4, 1 15, 12 13, 10 A poor solution: There are...
package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic * collection to store elements where indexes represent priorities and the * priorities can change in several ways. * * This collection class uses an Object[] data structure to store elements. * * @param <E> The type of all elements stored in this collection */ // You will have an error until you have have all methods // specified in interface PriorityList included inside this...
I'm writing this class called CharArrayProject_3 that removes repeating elements from an array of chars. However, when I run the driver class, it just outputs two sets of dashed lines. What am I getting wrong? Is it the deleteRepeats() method?: public class CharArrayProject_3 { private char[] array; privateint length; privateintnumberOfRepeats; public CharArrayProject_3( char[] arr ) { length = arr.length; array = new char[ length ]; numberOfRepeats = 0; for( int k = 0; k < arr.length; k++ ) { array[k]...
Using java fix the code I implemented so that it passes the JUnit Tests. MATRIX3 public class Matrix3 { private double[][] matrix; /** * Creates a 3x3 matrix from an 2D array * @param v array containing 3 components of the desired vector */ public Matrix3(double[][] array) { this.matrix = array; } /** * Clones an existing matrix * @param old an existing Matrix3 object */ public Matrix3(Matrix3 old) { matrix = new double[old.matrix.length][]; for(int i = 0; i <...
JAVA: array return types May you please help me fix this coding. Sum is SUPPOSE to be 1253 import java.util.Scanner; public class Array { public static int sum(int[] arr) { int i; int total = 0; for ( i =0; i < arr.length; ++i) { total = total + arr[i]; } return total; } public static void main(String[] args) { int[] myArray = {45, 22, 18, 89, 82, 79, 15, 69, 100, 55, 48, 72, 16, 98, 57, 75, 44,...
(JAVA) Given an array of unique positive integers, write a function findSums that takes the array input and: 1. Creates a hashtable called “hashT” and inserts all the elements of the input array in the hashtable. 2. Finds pairs of elements in the hashtable whose sum is another element (sum) in the hashtable and print the pairs in the console. 3. Returns another hashtable names “sums” of those sum elements. For example: Input: [1,5,4,6,7,9] Output: [6,5,7,9] Explanation: 6 = 1...
The code snippet below is an example of pass by reference. We also provide a sample method setZeroAt, which sets 0 at a position i in the array, to illustrate pass by reference. public class Sample { public static void setZeroAt(int [] arr, int i){ arr[i] = 0; } public static void main(String[] args) { Scanner input = new Scanner(System.in); int sample[] = {1, 2, 3}; setZeroAt(sample, 1); //Now sample looks like {1, 0, 3} } } Write a Java...