简体   繁体   中英

Removing a character from a sentence

I am writing a java program that removes a character from a sentence. I am getting an error that says: The method charAt(int) is undefined for the type java.Lang.String. [line 35]

Any suggestions what this means.

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);
}
}
String changedSentence = sentence.trim().CharAt(randomPosition);

It's charAt not CharAt . Nevertheless, if you made this change, you would still be trying to assign a char to a variable that should be holding a String . You can use Character.toString to convert a character to a string.


PS If you want to delete characters in strings use a StringBuilder :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM