gpt4 book ai didi

java.lang.StringIndexOutOfBoundsException : String index out of range: 异常

转载 作者:行者123 更新时间:2023-11-29 10:10:36 25 4
gpt4 key购买 nike

我知道有人问过类似的问题,但他们都有同样的问题:在循环内部他们有类似的东西

i <= aString.lenth()

我用过

i < phrase.length();

我仍然收到错误。我也试过了

i < phrase.length()-1;

知道哪里出了问题吗?

谢谢。

public class WordPlay {
public boolean isVowel(char c) {
if(c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U') {
return true;
}
else
{
return false;
}
}
public void testIsVowel () {
System.out.println(isVowel('F'));
}
public String replaceVowels (String phrase, char ch){
StringBuilder replaced = new StringBuilder(phrase);
for (int i = 0; i<phrase.length(); i++) {
char currChar = phrase.charAt(i);
if (isVowel(currChar)){

//the line below causes the error
replaced.setCharAt(currChar, ch);
}
}
return replaced.toString();
}
public void testReplaceVowels() {
System.out.println(replaceVowels("Hello World", '*'));

}
}

最佳答案

在您调用 StringBuilder.setCharAt

replaced.setCharAt(currChar, ch);

第一个参数应该是i,而不是currChar:

replaced.setCharAt(i, ch);

您应该传递要设置字符的索引而不是字符本身

currCharint 值可能比您的 StringBuilder 的长度高,这会导致异常,但如果不是,你会无一异常(exception)地得到奇怪的输出,这更糟糕。

关于java.lang.StringIndexOutOfBoundsException : String index out of range: 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37458856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com