-2

我正在编写一个从句子中删除一个字符的java程序。我收到一条错误消息:对于 java.Lang.String 类型,方法 charAt(int) 未定义。[第 35 行]

任何建议这意味着什么。

public class Ex1Program {

public void start() {

String sentence = getSentenceFromUser();
int randomPosition = getRandomPosition(sentence);
printCharacterToBeRemoved(sentence, randomPosition);
String changedSentence = removeCharacter(sentence, randomPosition);
printNewSentence(changedSentence);

}

private String getSentenceFromUser() { 
System.out.print("Enter a sentence :");
String sentence = Keyboard.readInput();
return sentence;
}
private int getRandomPosition(String sentence) {
int randomPosition = (int)(Math.random() * 14) +1;
return randomPosition;
}

private void printCharacterToBeRemoved(String sentence, int randomPosition) {
System.out.print("Removing " + sentence.charAt(randomPosition) + " from position " +                 randomPosition);

}

private String removeCharacter(String sentence, int randomPosition) {
String changedSentence = sentence.trim().CharAt(randomPosition);
return changedSentence;
}

private void printNewSentence(String changedSentence) {
System.out.print("New sentence is " + changedSentence);
}
}
4

1 回答 1

3
String changedSentence = sentence.trim().CharAt(randomPosition);

charAt不是CharAt。_ 尽管如此,如果您进行了此更改,您仍然会尝试将 a 分配给char应该持有 a 的变量String。您可以使用Character.toString将字符转换为字符串。


PS如果要删除字符串中的字符,请使用StringBuilder

String changedSentence = (new StringBuilder(sentence)).
                                         deleteCharAt(randomPosition).toString()
于 2013-05-31T22:30:29.017 回答