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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With