COMP2243 - Programming and Problem Solving

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Methods RightTriangle.java RightTriangleWithLoop.java Geometry.java PayrollWithMethod.java PayrollWithMethodLoop.java Palindrome.java GlobalAndLocal.java Overloading.java Overloading2.java MathMethods.java and MathProgram.java CaesarCipher.java



CaesarCipher Program


Description

Caesar Cipher is an ancient encryption technique. We can use it to transmit encrypted data.

To encrypt the text message, each character in the original message is shifted N positions, where N is called key.

For example, if N = 1, then the message

Computer Science

Becomes

Dpnqvufs!Tdjfodf

The encrypted message can be decrypted to the original message by shifting back every character N positions.

Shifting N positions forward and backward is achieved by adding or subtracting N to the character's ASCII code.

This program reads text data from a data file and N from the keyboard, then encrypts the text and saves the encrypted text to another file.

Note:

The ASCII value resulting from encryption should fall between 32 and 126 (printable characters).

For example, if the program adds 8 (value of N) to 122 (ASCII code for ‘z’), the result is 130 which is out of the range of printable characters.

So the program should “wrap around” to get 36. However, this program doesn't provide the solution of wrapping around.

Associated Concepts:

File I/O

Method

Algorithm:

main method:

Create a File object and associate it with the data file and
then create a Scanner object and associate it with the File object

Create a FileWriter object and associate it with the output file and
then create a PrintWriter object and associate it with the FileWriter object

Prompt the user to enter the encryption key

Call encrypt method and pass inFile, outFile, and key as arguments

Close both inFile and outFile objects

Write encrypt method definition

while loop (as long as the data file has data item):

    read the entire line of data

    Use a loop to retrieve each character in the line:

         Encrypt the character with the key (no wrap around)

         Append the encrypted character to the encrypted line

    Write the encrypted line to the output file

Source Code



Input File CaesarCipher_Data.txt



Sample Run



Output File CaesarCipher_Result.txt



Video