How to show sentence word by word in a separate line

Insane picture Insane · Oct 25, 2013 · Viewed 18.8k times · Source

The sentence String is expected to be a bunch of words separated by spaces, e.g. “Now is the time”. showWords job is to output the words of the sentence one per line.

It is my homework, and I am trying, as you can see from the code below. I can not figure out how to and which loop to use to output word by word... please help.

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

}

Answer

Simon Forsberg picture Simon Forsberg · Oct 25, 2013

Since this is a homework question, I will not give you the exact code but I want you to look at the method split in the String-class. And then I would recommend a for-loop.

Another alternative is to replace in your String until there are no more spaces left (this can be done both with a loop and without a loop, depending on how you do it)