我正在尝试编程这么久,它不会工作。我需要一个程序,它遵循以下内容:
用户输入:我正在寻找食物。我喜欢食物。 系统打印:食物有些看起来我。食物爱我。
反转单词,UpperWord第一个单词,从下一个句子开始,保持“。”在它的位置。
package finaledition;
public class finaledition {
public static void main(String[] args) {
StringBuilder outputString= new StringBuilder();
String satz;
String wort;
System.out.print("Bitte geben Sie einen String ein: ");
String text = Input.readString();
while (text.indexOf('.') > 0) {
satz = text.substring(0, text.indexOf('.'));
text = text.substring(text.indexOf('.') + 1);
while (satz.lastIndexOf(' ') > 0) {
wort = satz.substring(satz.lastIndexOf(' ') + 1);
outputString.append(wort);
satz = satz.substring(0, satz.lastIndexOf(' '));
}
System.out.print(outputString);
}
}
}
实际结果是:
foodsomeforlookingfoodsomeforlookingfoodlove
答案 0 :(得分:1)
首先,您需要将孔文本分成句子:
String[] sentences = text.split(". ");
然后你需要创建一个包含以下单词的数组:
String[] words = sentences[anIndex].split(" ");
然后,反转单词array:
String[] reverseSentence = new String[words.length];
for(int a=0; a<words.length; a++){
reverseSentence[a] = words[words.length - a -1];
}
然后将所有反向句子加在一起并添加一个&#39;。#。#。
答案 1 :(得分:1)
嵌套循环很难理解并导致错误和浪费时间试图dubug和理解程序代码,而不是你需要使用oop
,java是oop
语言。您需要创建完全解决问题的课程Sentence
。
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
final String userInput = "I´m looking for some food. I love food";
final String expectedResult = "Food some for looking I´m. Food love I.";
String[] sentences = userInput.split("\\. ");
String reversedSentences = Stream.of(sentences)
.map(sentenceString -> new Sentence(sentenceString))
.map(sentence -> sentence.reverse())
.map(sentence -> sentence.firstLetterToUpperCase())
.map(sentence -> sentence.removeAllDots())
.map(sentence -> sentence.dotInTheEnd())
.map(sentence -> sentence.toString())
.collect(Collectors.joining(" "));
System.out.println(reversedSentences.equals(expectedResult)); //returns true
}
}
final class Sentence {
private final String sentence;
Sentence(String sentence) {
this.sentence = sentence;
}
Sentence reverse() {
String[] words = sentence.split(" ");
Collections.reverse(Arrays.asList(words));
return new Sentence(String.join(" ", words));
}
Sentence firstLetterToUpperCase() {
String firstLetter = sentence.substring(0, 1);
String anotherPart = sentence.substring(1);
return new Sentence(firstLetter.toUpperCase() + anotherPart);
}
Sentence dotInTheEnd() {
return new Sentence(sentence + ".");
}
Sentence removeAllDots() {
return new Sentence(sentence.replaceAll("//.", ""));
}
@Override
public String toString() {
return sentence;
}
}