从句子中删除字符

时间:2013-05-31 22:29:13

标签: java algorithm

我正在编写一个从句子中删除字符的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);
}
}

1 个答案:

答案 0 :(得分:3)

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

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


P.S。如果要删除字符串中的字符,请使用StringBuilder

String changedSentence = (new StringBuilder(sentence)).
                                         deleteCharAt(randomPosition).toString()