Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Exercise 2: Write a Java program (called Lab6Exercise2)to read a sentence (as a

ID: 3872351 • Letter: E

Question

Exercise 2: Write a Java program (called Lab6Exercise2)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. (NOTE: The only methods from the Java standard library class String which may be used in this exercise are length(), charAt(), and trim0).) Entered String: This is a test input, and can be a longer string too. Word Word Word Word Word Word Word Word Word Word Word Word #1: #2: #3: #4: #5: #6: #7: #8: #9: #10: #11: #12: This is test input, and can be longer string too.

Explanation / Answer

Create a file app.java and paste given code into it! Filename must be app.java.

app.java

import java.util.Scanner;
public class app {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the sentence!" );
String tmp;
tmp = scanner.nextLine();   
String[] words = tmp.split("\s");
for(int i = 0; i< words.length ;i++)
{
System.out.println("Word #:" + (i+1) + " " + words[i]);
}

}
  
}

Sample Output:

Enter the sentence!

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!