0

此方法应该接受一个字符串并将字符串输出为字符,但它应该是两倍大小。示例:字符串为 "PaRty" 返回应为 'P', 'P', 'a', 'a', 'R', 'R', 't', 't', 'Y', 'Y'

对于我的代码,当我运行测试时,它说数组在元素 [];expected: 处不同,但是:

我不知道是错的,希望有人能帮我指出一些事情让我理解并完成这项工作吗?如果我落后一个,请解释一下?

//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;
4

2 回答 2

4

您的复制逻辑不正确。您需要将字母从索引复制i到索引2*i2*i + 1. 最后i++是不必要的;它已经在for循环中完成了。改变

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

charArray[2*i] = string.charAt(i);
charArray[2*i+1] = string.charAt(i);
于 2014-04-17T17:57:13.850 回答
0
string.charAt(i)

不正确,应该是

string.charAt(i/2)

你每次循环增加 i 两次。

于 2014-04-17T17:58:39.377 回答