句子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/

10-13 04:11