Write a Java program to read a sentence (as a single string) from the user, the
ID: 3671335 • Letter: W
Question
Write a Java program to read a sentence (as a single string) from the user, the program then prints out the entered sentence. Then utilize loops to print out the sentence one word per line using the space (blank) character as the delimiter. (Your program should be able to handle instances of multiple spaces between words and the possibility that there are spaces at the beginning and end of the sentence.) Use proper labels and line up the outputs as shown in the examples below. Design your program to allow the user to re-run the program with a different input. Entered String: This is a test input, and can be a longer string too. Please no arrays or hasNext(hasnextLine is acceptable). Thank you.
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
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) { String[] words = sentence.split(' '); for(String word : words) { System.out.println(word); } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.