So, I have to write a new class method called "insert." What insert does, is it takes the arguments Item[] array, Item newitem, and int k, and it inserts new item into the array at index k.
Part of this code I can change, and part of it I can't. Here is the part I can't change:
Instructions as originally put:
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 unchangeable 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 small segment I can change:
public static void insert( Item[] array, Item newItem, int k )
{
a[i] = a[i + 1];
}
// that's all I can change
}
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.
UPDATE:
I tried it like this:
public static void insert( Item[] array, Item newItem, int k )
{
for (int i = 0; i < array.length()-1; i++){
array[i] = array[i-1];
}
}
I still get the same error, just with the first line of the for-loop instead of "array[i] = array[i-1]" in the error message.