Design (pseudocode) (name it Words) to read a sentence (as a string) from the us
ID: 3754696 • Letter: D
Question
Design (pseudocode) (name it Words) to read a sentence (as a string) from the user and prints out the entered sentence followed by each word as shown below. Document your code and properly label the input prompts and the outputs as shown below.
Sample run 3:
Entered String: This is a test.
Word #1: This
Word #2: is
Word #3: a
Word #4: test.
Sample run 2:
Entered String: Hello there!
Word #1: Hello
Word #2: there!
Sample run 3:
Entered String: This is a test input, and can be a longer string too.
Word #1: This
Word #2: is
Word #3: a
Word #4: test
Word #5: input,
Word #6: and
Word #7: can
Word #8: be
Word #9: a
Word #10: longer
Word #11: string
Word #12: too.
Explanation / Answer
Words.java
import java.util.Scanner;
public class Words {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the String: ");
String s = scan.nextLine();
Scanner words = new Scanner(s);
int i=1;
while(words.hasNext()) {
System.out.println("Word #"+i+": "+words.next());
i++;
}
}
}
Output:
Enter the String:
This is a test input, and can be a longer string too.
Word #1: This
Word #2: is
Word #3: a
Word #4: test
Word #5: input,
Word #6: and
Word #7: can
Word #8: be
Word #9: a
Word #10: longer
Word #11: string
Word #12: too.