-6

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.

user3363511
  • 79
  • 1
  • 1
  • 7

2 Answers2

0

In your code, i is not defined. a neither. You need to write some code here to move all the elements after k to the end of the array.

Nicolas Defranoux
  • 2,646
  • 1
  • 10
  • 13
  • What sort of code would move all of the elements after k up by one? I'm just wondering like conceptually, what do I do? – user3363511 Mar 01 '14 at 21:50
  • A for loop would do it, but moving the last one first so that you don't overwrite each one. for(int i = ... ; i > ... ; --i) array[i] = array[i-1]; – Nicolas Defranoux Mar 01 '14 at 21:54
0

This could never compile. The reason is that you never declare the variable named "a" or the variable named "i"

Stephen
  • 2,613
  • 1
  • 24
  • 42
  • It wasn't defined in the part I couldn't edit. And there's no part before where they edit it, that is editable. Can I define something in the code AFTER that segment of code? – user3363511 Mar 01 '14 at 21:20