Question

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 the caller method

public static void printFile(String fileName, final int[] array) 
           throws IOException {
      File file = new File(fileName);
      PrintWriter out = new PrintWriter(file);
      for (int i = 0; i < array.length; i++) {
          out.println(array[i]);
      }
      out.close();
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Question 1:

Answer:

The updated method is given below:

public E get(int index) throws IndexOutOfBoundsException {
if (index < 0 || index > numItems) {
//System.out.println("Get error: Index "+ index + " is out of bounds.");
//the below statement will throw and IndexOutOfBoundsException exception
throw new IndexOutOfBoundsException(String.format("Get error: Index "+ index + " is out of bounds"));
//return null;
}
return array[index];
}

Question 2:

Answer:

The updated method is given below:

public static void printFile(String fileName, final int[] array) {
//try block
try() {
File file = new File(fileName);
PrintWriter out = new PrintWriter(file);
for (int i = 0; i < array.length; i++) {
out.println(array[i]);
}
out.close();
}
//catch block
catch (IOException e) {
           e.printStackTrace();
}
}   

Add a comment
Know the answer?
Add Answer to:
JAVA PROBLEMS 1. Update the below method to throw an IndexOutOfBoundsException: public E get(int index) {...
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
  • Use JAVA language. public class DynamicArray2 { private String[] data; // the backing array private int...

    Use JAVA language. public class DynamicArray2 { private String[] data; // the backing array private int virtualArrayLength; // the number of elements in the dynamic array // Throws an IndexOutOfBoundsException if i is not a valid index // for adding to the dynamic array, otherwise inserts s at index i. // Elements can be added from index 0 to this.size(). public void add(int i, String s) { // If there is no room for s in data, create a new...

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

  • Complete an Array-Based implementation of the ADT List including a main method and show that the...

    Complete an Array-Based implementation of the ADT List including a main method and show that the ADT List works. Draw a class diagram of the ADT List __________________________________________ public interface IntegerListInterface{ public boolean isEmpty(); //Determines whether a list is empty. //Precondition: None. //Postcondition: Returns true if the list is empty, //otherwise returns false. //Throws: None. public int size(); // Determines the length of a list. // Precondition: None. // Postcondition: Returns the number of items in this IntegerList. //Throws: None....

  • 1. Write a complete program based on public static int lastIndexOf (int[] array, int value) {...

    1. Write a complete program based on public static int lastIndexOf (int[] array, int value) { for (int i = array.length - 1; i >= 0; i--) { if (array [i] == value) { return i; } } return -1; write a method called lastindexof that accepts an array of integers and an integer value as its parameters and returns the last index at which the value occurs in the array. the method should return -1 if the value is...

  • COMPLETE THE BUCKETSORT METHOD public static void bucketSort(int[] array) {        int bucketCount = array.length/2;...

    COMPLETE THE BUCKETSORT METHOD public static void bucketSort(int[] array) {        int bucketCount = array.length/2;        int minIntValue = 0;        int maxIntValue = array.length - 1;        // Create bucket array        List<Integer>[] buckets = new List[bucketCount];        // Associate a list with each index in the bucket array           for(int i = 0; i < bucketCount; i++){            buckets[i] = new LinkedList<>();        }        //...

  • Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class...

    Can someone help me with my Java code error! Domain package challenge5race; import java.util.Random; public class Car {    private int year; private String model; private String make; int speed; public Car(int year, String model, String make, int speed) { this.year = year; this.model = model; this.make = make; this.speed = speed; } public Car() { } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public String getModel() { return model; }...

  • JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final...

    JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final int DEFAULT_CAPACITY = 2;   //default initial capacity / minimum capacity    private T[] data;   //underlying array    // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!       @SuppressWarnings("unchecked")    public SmartArray(){        //constructor        //initial capacity of the array should be DEFAULT_CAPACITY    }    @SuppressWarnings("unchecked")    public SmartArray(int initialCapacity){        // constructor        // set the initial capacity of...

  • Improve the speed of public T get(int i) by having it work backward from the end...

    Improve the speed of public T get(int i) by having it work backward from the end of the array if you attempt to get a member which is closer to the end than the start. This improvement will be tested through timing tests on large lists. The method should still return null if i is not a valid index. Code import java.util.Iterator; public class DLList<T> implements Iterable<T> {    private static class Node<T> {        public Node<T> prev, next;...

  • [Java] I need help completing the method below. The instructions are also below. public int wordSearch(String...

    [Java] I need help completing the method below. The instructions are also below. public int wordSearch(String word, String filename) { } - find the first time the word appears in a text file filename and returns the position of the word in the file(if its the first word in the file, method should return 1) - assume no punctuation in file - assume all whitespace is either a new line or single space - do not include the times that...

  • Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming)...

    Using java socket programming rewrite the following program to handle multiple clients simultaneously (multi threaded programming) import java.io.*; import java.net.*; public class WelcomeClient { public static void main(String[] args) throws IOException {    if (args.length != 2) { System.err.println( "Usage: java EchoClient <host name> <port number>"); System.exit(1); } String hostName = args[0]; int portNumber = Integer.parseInt(args[1]); try ( Socket kkSocket = new Socket(hostName, portNumber); PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(kkSocket.getInputStream())); ) { BufferedReader...

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