i need to write a method that takes a char array, an int, and a char value as parameters and add the char value after the bucket number represented by the int in the char array, moving everything else down one spot. i think i am close. Right now i can get the char parameter to replace the the char already there but i need to add it after the char thats already there. Heres my code so far:
Code:
static char[] addArray (char[] x, int e, char y)
{
char[] result = new char[x.length+1];
x[e+1] = y;
result = x;
return result;
}
Your creation of the new char array is fine.
Next step. For loop for the length of the new char array.
In the body of the loop, check to see if you at the the bucket position, if not, add the char from the old array at loop position, assuming you started at zero.
Now to check for bucket position. Say it is 6. You want position 5 in the array, unless you mean that 6 means 6.
Once he hit the bucket position, add to the char array the new value.
Now, all you have to do is add the rest of the old values. These are actually going to be loop position - 1. Hope this helps.
ok so i followed what you said this is what i got so far. it compiles ok but then comes up with an array index out of bounds exception. what am i doing wrong?
Code:
static char[] addArray (char[] x, int e, char y)
{
char[] result = new char[x.length+1];
for (int i = 0; i < result.length; i++)
{
if(i != e)
result[i] = x[i];
if (i == e)
result[e] = y;
}
return result;
}
As long as you are consider that your arrays start at zero, just compare the index of the loop, i, with your bucket position. If equal, put the new value in the position. If i < bucket, just put the ith position of the old array into the new array at the ith position. If i > bucket, put the ith - 1 position of the old array into the ith position of the new array.
There may be a slightly neater way of doing this, but this was the first method i thought of.
So, you should have 3 conditions. You can use else if statements as well.
ok so now this is what i have for the char to be added i put in 'z' and when it returns result it just returns z in the e position of the char array it does not write any of the other characters.
Code:
static char[] addArray (char[] x, int e, char y)
{
char[] result = new char[x.length+1];
for (int i = 0; i < result.length; i++)
{
if (i == e)
result[e] = y;
if (i < e)
x[i] = result[i];
if (i > e)
x[i-1] = result[i];
}
return result;
}