Hi, so here's the problem. I don't really get the concept of how I "insert" an item into an array. I get a cannot find symbol error when I try to. I think its because I'm losing focus. Could someone clarify what sort of code would "insert" an item into an array please? I just want a goal of conceptually how I would do it.
Anyways, here are the instructions for the exercise:
Write a new class method, insert, for the Item class that takes three arguments — an Item[] array, an Item newItem, and an int k — and inserts newItem into array at index k, discarding the last item of the array (that is, the item originally at index array.length - 1).
Here is the uneditable code:
public class Item { private int myN; public Item( int n ) { myN = n; } public String toString() { return "Item:" + myN; } public int getN() { return myN; } public static Item[] makeItemArray( int len ) { Item[] a = new Item[ len ]; int i; for ( i = 0 ; i < len ; i++ ) a[ i ] = new Item( i ); return a; } public static void displayArray( Item[] array ) { for ( Item item : array ) System.out.println( item ); }
This part only I can edit:
public static void insert( Item[] array, Item newItem, int k ) { array[i - 1] = array[i]; }
But this part onward, I can't.
} public class MainClass { public static void main( String[] args ) { Item[] array = Item.makeItemArray( ); System.out.println( "Before: " ); Item.displayArray( array ); // make a new Item Item newItem = new Item( 99 ); // insert the new item Item.insert( array, newItem, ); System.out.println( "\nAfter: " ); Item.displayArray( array ); } }
I get a cannot find symbol error, but I thought I was doing as I was supposed to. I thought you had to have an ArrayList to be able to insert or delete an item from an array. How can you take a primitive object, like an array, and insert something into it. My idea of it was a[i] would be replaced with a[i + 1]. I know I'm getting this concept wrong because that's what I tried to do.
Anyways, I've been really tired today and need a little bit of help because I'm having trouble keeping my thoughts straight today. I really appreciate the help.
Sincerely, your pupil, ghostheadx
PS: I am about to start Lab 28 if I get help today, which would make me caught up with my class, so today it's extremely important that I do this exercise correctly.