How to break the 4 words using substring method
I'm wanting to break up a sentence consisting of 4 words, into individual
words. But, I'm not sure how to tell it to start from after the first
space and stop and the next space in the sentence.
import java.util.Scanner;
public class arithmetic {
public static void main(String[] args) {
Scanner in = new Scanner(System.in)
String sentence;
String word1, word2, word3, word4;
int p, p2;
System.out.print("Enter a sentence with 4 words:");
sentence = in.nextLine();
p = sentence.indexOf(" ");
word1 = sentence.substring(0,p)+(" ");
word2 = sentence.substring()(" ");
word3 = sentence.substring()+(" ");
word4 = sentence.substring()+(" ");
sentence = word1+word2+word3+word4;
System.out.println(sentence);
No comments:
Post a Comment