0

This method is supposed to take in a string and output the string as chars however it should be double the size. Example: the string is "PaRty" return should be 'P', 'P', 'a', 'a', 'R', 'R', 't', 't', 'Y', 'Y'

For my code, when I run the test it says that the arrays differed at element [];expected: but was:

I can not figure out was is wrong and was hoping someone can help point something out for me to understand and make this work please? And if I am off by one please explain?

//Implementing the second method: toExpandedArray, which works with 
//a string and then returns chars of that string. 
public static char[] toExpandedArray(String string)
{
    //Initializing variable needed to char the string
    char[] charArray = new char[string.length() * 2];     

    //The loop that will turn the string into characters.
    for (int i = 0; i < string.length(); i++)
    {            
     charArray[i] = string.charAt(i) ;
     charArray[i+1] = charArray[i];
     i++;
    }

    //Returning the characters as an array.
    return charArray;

2 Answers2

4

Your copying logic is incorrect. You need to copy the letter from index i to index 2*i and 2*i + 1. The i++ at the end is unnecessary; it's already done in the for loop. Change

charArray[i] = string.charAt(i);
charArray[i+1] = charArray[i];
i++;

to

charArray[2*i] = string.charAt(i);
charArray[2*i+1] = string.charAt(i);
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Thank you! Is the reason for 2*i because of the previous charArray initialized as string.length * 2? – user3404391 Apr 17 '14 at 18:13
  • So that the character at `0` gets copied to `0` and `1`, the character at `1` gets copied to `2` and `3`, the character at `2` gets copied to `4` and `5`, and so on. – rgettman Apr 17 '14 at 18:14
0
string.charAt(i)

is incorrect, it should be

string.charAt(i/2)

you increment i twice each loop.

GriffinG
  • 662
  • 4
  • 13