Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show sentence word by word in a separate line

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

}
like image 225
Insane Avatar asked Oct 21 '22 22:10

Insane


1 Answers

You're on the right path. Your showWords method works for the first word, you just have to have it done until there are no words.

Loop through them, preferably with a while loop. If you use the while loop, think about when you need it to stop, which would be when there are no more words.

To do this, you can either keep an index of the last word and search from there(until there are no more), or delete the last word until the sentence string is empty.

like image 155
mau Avatar answered Oct 23 '22 21:10

mau