句子 String 应该是一堆由空格分隔的单词,例如“现在是时候了”。 showWords 的工作是每行输出一个句子的单词。
这是我的功课,我正在努力,正如您从下面的代码中看到的那样。我不知道如何以及使用哪个循环来逐字输出...请帮忙。
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence");
String sentence = in.nextLine();
showWords(sentence);
}
public static void showWords(String sentence) {
int space = sentence.indexOf(" ");
sentence = sentence.substring(0,space) + "\n" + sentence.substring(space+1);
System.out.println(sentence);
}
}
最佳答案
您走在正确的道路上。您的 showWords 方法适用于第一个单词,您只需要完成它直到没有单词。
遍历它们,最好使用 while 循环。如果您使用 while 循环,请考虑何时需要它停止,也就是没有更多单词的时候。
为此,您可以保留最后一个单词的索引并从那里搜索(直到没有更多),或者删除最后一个单词直到句子字符串为空。
关于java - 如何在单独的行中逐字显示句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19578417/