Click here to Skip to main content
15,940,921 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
so i have this problem online that when i try to test it it works but when the website that i am taking the course on tries it it is always wrong!!
This is the question!!
i am trying to make a method that add an element at a specific index!
In this exercise you’ll get a chance to improve our expanding array to add some of the other functionality that you get in ArrayList.

You should add three methods:

public void add(int index, int element)
public int remove(int index)
public int size()


What I have tried:

int newSize = currentSize + 1;
        int[] newArray = new int[newSize];
        // Copy over old elements
        for(int i = 0; i < index; i++)
            newArray[i] = arr[i];
        newArray[index] = element;
        for(int i = index; i < newSize-1; i++)
            newArray[i+1] = arr[i];
        newArray[newSize-1] = arr[currentSize-1];
        arr = newArray;
        currentSize = newSize;
Updated 29-Nov-18 23:29pm
Patrice T 29-Nov-18 18:51pm    
Why you don't ask them the reason ?
If they can't tell you, take courses from another site.

We can't give you the answer because we don't even know what is that site.

Probably because you aren't testing all possible cases, and they are.

Start by setting up an array of known size - 5 elements maybe - and known values - {10, 11, 12, 13, 14} and use your add method to add an element at each possible index: 0, 1, 2, ... Does it work for each test case? Do you get out exactly what you expected? Why not? What did you expect? How does that differ from what you expected?

When you have that, you can start looking at your code to find out why.

I'll give you a hint: No, you don't ...
Share this answer
Go to The Java™ Tutorials[^] and work through the first three or four first. That should give you a good understanding of the basics of the language, and some of the essential classes that are available.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900