gpt4 book ai didi

从句子中删除字符的Java程序

转载 作者:行者123 更新时间:2023-12-01 08:11:35 24 4
gpt4 key购买 nike

我正在编写一个java程序,从句子中删除一个字符。我的代码是;

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;
}

int sentenceLength = sentence.length();
int randomPosition = (int)(Math.random() * sentenceLength) + 0;
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.deleteCharAt(randomPosition);
return changedSentence;
}

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

当我编译时,我收到一条错误消息:

Error: cannot find symbol symbol: method deleteCharAt(int) location: variable sentence of type java.lang.String

我花了几个小时试图解决这个问题,所以非常感谢您的帮助。

最佳答案

String 类没有 deleteCharAt 方法。 StringBuilder 有。

这样做:

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

我建议使用 Netbeans 或 Eclipse 等 IDE。这些开发工具会立即告诉您发生了什么。

关于从句子中删除字符的Java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16869085/

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