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

Java Programming Task #2 String.split and the StringBuilder Class 1. Copy the fi

ID: 3838499 • Letter: J

Question

Java Programming

Task #2 String.split and the StringBuilder Class

1. Copy the file secret.txt (Code Listing 9.3) from the Student CD or as directed by your instructor. This file is only one line long. It contains 2 sentences.

2. Write a main method that will read the file secret.txt, separate it into word tokens.

3. You should process the tokens by taking the first letter of every fifth word, starting with the first word in the file. Convert these letters to uppercase and append them to a StringBuilder object to form a word which will be printed to the console to display the secret message.

Code Listing 9.3 (secret.txt)

January is the first month and December is the last. Violet is a purple color as are lilac and plum.

Explanation / Answer

StringBuilderTest.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class StringBuilderTest {

   public static void main(String[] args) throws FileNotFoundException {
       File file = new File("D:\secret.txt");
       Scanner scan = new Scanner(file);
       String line = scan.nextLine();
       String tokens[] = line.split("\s+");
       StringBuilder sb = new StringBuilder();
       for(int i=0;i<tokens.length;i++){
           if(i % 5 ==0 ){
               sb.append(tokens[i].toUpperCase().charAt(0));
           }
       }
       System.out.println("secret message is "+sb.toString());
   }

}

Output:

secret message is JAVA

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote