30.6k views
3 votes
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 andappend them to a StringBuilder object to form a word which will be printedto the console to display the secret message.

User Bob Jones
by
4.8k points

1 Answer

4 votes

Answer:

See explaination

Step-by-step explanation:

import java.io.File;

import java.io.IOException;

import java.util.Scanner;

import java.util.StringTokenizer;

public class SecretMessage {

public static void main(String[] args)throws IOException

{

File file = new File("secret.txt");

StringBuilder stringBuilder = new StringBuilder();

String str; char ch; int numberOfTokens = 1; // Changed the count to 1 as we already consider first workd as 1

if(file.exists())

{

Scanner inFile = new Scanner(file);

StringTokenizer line = new StringTokenizer(inFile.nextLine()); // Since the secret.txt file has only one line we dont need to loop through the file

ch = line.nextToken().toUpperCase().charAt(0); // Storing the first character of first word to string builder as mentioned in problem

stringBuilder = stringBuilder.append(ch);

while(line.hasMoreTokens()) { // Looping through each token of line read using Scanner.

str= line.nextToken();

numberOfTokens += 1; // Incrementing the numberOfTokens by one.

if(numberOfTokens == 5) { // Checking if it is the fifth word

ch = str.toUpperCase().charAt(0);

stringBuilder = stringBuilder.append(ch);

numberOfTokens =0;

}

}

System.out.println("----Secret Message----"+ stringBuilder);

}

}

}

User Razgriz
by
4.7k points