I’m working on a project with arrays. I’m using a method that adds values to an array of size 20. I’m supposed to be able to change the size of the array while also transferring values from the previous array into the new array. I used Array.copyOfRange which should work but for some reason when I run the code and try changing the size of the array. I get an Error Message that says Index out of bounds. Could someone help me figure out why it would say that when this should work?
import java.util.Scanner; import java.util.Arrays; public class IntBag2 { private static final int INITIAL_SIZE = 20; private static int[] bag; private int capacity; public IntBag2() { bag = new int[INITIAL_SIZE]; } public IntBag2(int capacity) { bag = new int[capacity]; } public boolean add(int item) { if (capacity == bag.length) return false; bag[capacity++] = item; return true; } public void changeCapacity(int newCapacity) { bag = Arrays.copyOfRange(bag, 0, newCapacity); } @Override public String toString() { String result = "Bag: "; for (int i = 0; i < capacity; i++) result += bag[i] + " "; return result; } public static void main(String[] args) { Scanner input = new Scanner(System.in); IntBag2 intBag = new IntBag2(); boolean done = false; while (!done) { System.out.println("1. Add an Item to the Array"); System.out.println("2. Change Length of Array"); System.out.println("3. toString"); switch (input.nextInt()) { case 1: System.out.println("Add an Item to the Array"); intBag.add(input.nextInt()); break; case 2: System.out.println("Change Length of Array"); intBag.changeCapacity(input.nextInt()); break; case 3: System.out.println("toString"); System.out.println(intBag.toString()); break; } } input.close(); } }
Advertisement
Answer
Because in your changeCapacity function you are not updating the capacity field with the newCapacity being passed.
public void changeCapacity(int newCapacity) { bag = Arrays.copyOfRange(bag, 0, newCapacity); capacity = newCapacity; }
Just replace your changeCapacity function with above code and it should work fine.