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

NaiveEncryption.java This same functionality can be written in far fewer lines o

ID: 3877423 • Letter: N

Question

NaiveEncryption.java

This same functionality can be written in far fewer lines of code if a StringTokenizer and StringBuilder were used.

Write a program that achieves the same task as the one in the file NaiveEncryption, but which can be coded with fewer the 10 lines of code.

public class NaiveEncryption {

public static void main(String[] args) {

// setup a scanner object, and receive user's input
Scanner keyboard = new Scanner(System.in);
System.out.print("Provide an input sentence: ");
String input = keyboard.nextLine();

System.out.print("The output sentence is : ");
String intermediateWord = "";
for (int i = 0; i < input.length(); i++) {
if (input.substring(i, i + 1).equals(" ") || (i + 1) == input.length()) {
if ((i + 1) == input.length()) {
intermediateWord += input.substring(i, i + 1);
}
for (int j = intermediateWord.length() - 1; j > -1; j--) {
System.out.print(intermediateWord.substring(j, j + 1));
}
intermediateWord = "";
System.out.print(" ");
} else {
intermediateWord += input.substring(i, i + 1);
}
}
System.out.println("");
}
}

Explanation / Answer

Hello, I have a solution for you. Implemented everything as per the requirements. Defined following things in this answer.

//NaiveEncryption.java

import java.util.Scanner;

import java.util.StringTokenizer;

public class NaiveEncryption {

      public static void main(String[] args) {

            // setup a scanner object, and receive user's input

            Scanner keyboard = new Scanner(System.in);

            System.out.print("Provide an input sentence: ");

            /**

            * Tokenizing the input by white space (dividing)

            */

            StringTokenizer input = new StringTokenizer(keyboard.nextLine(), " ");

            StringBuilder output = new StringBuilder();

            /**

            * Iterate through all the tokens (words)

            */

            while (input.hasMoreTokens()) {

                  /**

                  * Creating a StringBuilder object from the word

                  */

                  StringBuilder str = new StringBuilder(input.nextToken());

                  /**

                  * Appending the reverse of the word by calling reverse() method of

                  * StringBuilder to the output string

                  */

                  output.append(" " + str.reverse());

            }

            System.out.print("The output sentence is : " + output);

      }

}

/*OUTPUT*/

Provide an input sentence: hello world, how are you folks doing?

The output sentence is : olleh ,dlrow woh era uoy sklof ?gniod