Question

You will be writing a simple Java program that implements an ancient form of encryption known...

You will be writing a simple Java program that implements an ancient form of encryption known as a substitution cipher or a Caesar cipher (after Julius Caesar, who reportedly used it to send messages to his armies) or a shift cipher. In a Caesar cipher, the letters in a message are replaced by the letters of a "shifted" alphabet. So for example if we had a shift of 3 we might have the following replacements: Original alphabet: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Shifted alphabet: D E F G H I J K L M N O P Q R S T U V W X Y Z A B C Punctuation, numbers, and other non-alphabetic characters are unaffected by the shift. So the message "EAT AT JOE'S AT 1:00" becomes "HDW DW MRH'V 1:00". You will be writing a Java program that prompts the user to enter a file name, then reads the text from that file, applies a Caesar cipher to it, and then outputs the result to another file of the user's choice. The code must work for uppercase and lowercase letters and must work correctly if punctuation and numbers are included in the message. A "skeleton" of this code is provided below. NOTE: If you haven't noticed from the text above, only letters should have ROT-13 applied to them for this assignment. Anything else - punctuation, numbers, etc. - should be left untouched. You can use the functions Character.isLetter(), Character.isLowerCase() and Character.isUpperCase() to test if a character is an uppercase or lowercase letter or not. boolean test1 = Character.isLetter('A'); // test1 will be true boolean test2 = Character.isUpperCase('A'); // test2 will be true boolean test3 = Character.isLowerCase('A'); // test3 will be false boolean test4 = Character.isLetter('?'); // test4 will be false boolean test5 = Character.isUpperCase('a'); // test5 will be false boolean test6 = Character.isLowerCase('a'); // test6 will be true You can see more utility methods for working with the char type in the Character API documentation. NOTE 2: The shift method for this project requires you to change characters in a String based on changing individual characters. While there are many ways to do this, some will be easier than others. One way to do this easily is to take advantage of a String constant with all of the letters in a single String in order: private final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; With this setup, each character is represented as a numeric value by its index in the String, and we can manipulate the characters using simple math. For example, this code snippet should display the letter 'C': int myA = letters.indexOf("A"); int idxA = myA+2; char coded = letters.charAt(idxA); System.out.println(coded); Note that you cannot just add your shift value to every index to get the encoded value - for example, adding 2 to the index value for the letter 'Z' gives you an index of 27, which is outside the bounds of the String. But 'Z' shifted by 2 should be the letter 'B' because the cipher requires that we wrap around to the beginning when we go past our final letter. You will need to implement the logic to allow your characters to "wrap around" yourself. There are many different ways you can approach this, but as a hint consider using the remainder operation (%) to get your indices to circle back around. The constant letters is already included in the code skeleton provided in the link above. NOTE 3: Your shift method must work with negative numbers. If you provide a negative number to your shift it should move to the left instead of to the right. For example, the following code snippet should display the character 'X': int myZ = letters.indexOf("Z"); int idxZ = myZ-2; char coded = letters.charAt(idxZ); System.out.println(coded); Note that as in the case of a positive shift, the negative shift must also "wrap around" correctly - the letter 'A' shifted left by 2 should result in a 'Y', not in an index out of bounds exception. Note that if you have correctly implemented the shift method to work for both positive and negative values, you can use it to both encode and decode messages. To decode a message, just shift it back the negative amount you shifted it to encode it. For example, if you encoded a message with a shift of 3, you can shift the coded message by -3 to get the original message back. /** * YOUR DESCRIPTION HERE * @author YOUR NAME HERE * @version DATE HERE */ import java.util.Scanner; public class SubstitutionCipher { /** * Private constants used to shift characters for the substitution cipher. */ private static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz"; /** * Constructs a new String where each letter in the String input is shifted * by the amount shift to the right, preserving whether the original * character was uppercase or lowercase. For example, the String "ABC" with * shift 3 would cause this method to return "DEF". A negative value should * shift to the left. For example, the String "ABC" with shift -3 would * cause this method to return "XYZ". Punctuation, numbers, whitespace and * other non-letter characters should be left unchanged. * * @param input * String to be encrypted * @param shift * Amount to shift each character of input to the right * @return the encrypted String as outlined above */ public static String shift(String input, int shift) { // TODO - complete this function // TODO - the following line is only here to allow this program to // compile. Replace it and remove this comment when you complete // this method. return null; } /** * Displays the message "promptMsg" to the user and reads the next full line * that the user enters. If the user enters an empty string, reports the * error message "ERROR! Empty Input Not Allowed!" and then loops, * repeatedly prompting them with "promptMsg" to enter a new string until * the user enters a non-empty String * * @param in * Scanner to read user input from * @param promptMsg * Message to display to user to prompt them for input * @return the String entered by the user */ public static String promptForString(Scanner in, String promptMsg) { // TODO - complete this function // TODO - the following line is only here to allow this program to // compile. Replace it and remove this comment when you complete // this method. return null; } /** * Opens the file inFile for reading and the file outFile for writing, * reading one line at a time from inFile, shifting it the number of * characters given by "shift" and writing that line to outFile. If an * exception occurs, must report the error message: "ERROR! File inFile not * found or cannot write to outFile" where "inFile" and "outFile" are the * filenames given as parameters. * * @param inFile * the file to be transformed * @param outFile * the file to write the transformed output to * @param shift * the amount to shift the characters from inFile by * @return false if an exception occurs and the error message is written, * otherwise true */ public static boolean transformFile(String inFile, String outFile, int shift) { // TODO - complete this function // TODO - the following line is only here to allow this program to // compile. Replace it and remove this comment when you complete // this method. return false; } /** * Prompts the user to enter a single character choice. The only allowable * values are 'E', 'D' or 'Q'. All other values are invalid, including all * values longer than one character in length, however the user is allowed * to enter values in either lower or upper case. If the user enters an * invalid value, the method displays the error message "ERROR! Enter a * valid value!" and then prompts the user repeatedly until a valid value is * entered. Returns a single uppercase character representing the user's * choice. * * @param in * Scanner to read user choices from * @param allOptions * true if E and D are allowable inputs, false otherwise * @return the user's choice as an uppercase character */ public static char getChoice(Scanner in) { // TODO - complete this function // TODO - the following line is only here to allow this program to // compile. Replace it and remove this comment when you complete // this method. return 0; } /** * Displays the menu of choices to the user. */ public static void displayMenu() { System.out.println("[E]ncode a file"); System.out.println("[D]ecode a file"); System.out.println("[Q]uit"); } public static void main(String[] args) { Scanner in = new Scanner(System.in); displayMenu(); // TODO - complete this procedure with your own implementation in.close(); } } You must fill in the appropriate code. Pay close attention to what each method should be doing based on the information given in the comments before the method. You may add more methods to this skeleton if you feel that it would be useful, but if you do, remember to include comments on your added methods. Note that a method named displayMenu() has been provided for you to correctly display the menu for the user to use. A transcript of how this program should work is given below. [E]ncode a file [D]ecode a file [Q]uit Enter your choice: E Enter an input file: test.txt Enter an output file: test_encoded.txt Enter a shift amount: 13 Finished writing to file. [E]ncode a file [D]ecode a file [Q]uit Enter your choice: D Enter an input file: test_encoded.txt Enter an output file: test_decoded.txt Enter a shift amount: 13 Finished writing to file. [E]ncode a file [D]ecode a file [Q]uit Enter your choice: Q Goodbye! The above transcript uses the file test.txt as input. It contains the following text: This is a test! The Quick Brown Fox Jumped Over the Lazy Dog. This is only a test, but it should still work! What will this file hold? 3 + 3 = 6 and 3 * 3 = 9 The above transcript creates the file test_encoded.txt. After the program finishes, it contains the following text: Guvf vf n grfg! Gur Dhvpx Oebja Sbk Whzcrq Bire gur Ynml Qbt. Guvf vf bayl n grfg, ohg vg fubhyq fgvyy jbex! Jung jvyy guvf svyr ubyq? 3 + 3 = 6 naq 3 * 3 = 9 The above transcript also creates the file test_decoded.txt. After the program finishes, it contains the same text as test.txt. NOTE: There are no separate test cases for the method transformFile. However there are separate test cases for the output of your program to the screen and the output produced by your program to a file. You will not be able to test transformFile through this interface until you have the main method written, but you will be able to test each of the other methods individually (and you can - and should! - write your own tests to convince yourself that your transformFile method is working properly).

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

public class SubstitutionCipher {

        /**
         * Private constants used to shift characters for the substitution cipher.
         */
        private static final String UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private static final String LOWERCASE = "abcdefghijklmnopqrstuvwxyz";

        /**
         * Constructs a new String where each letter in the String input is shifted by
         * the amount shift to the right, preserving whether the original character was
         * uppercase or lowercase. For example, the String "ABC" with shift 3 would
         * cause this method to return "DEF". A negative value should shift to the left.
         * For example, the String "ABC" with shift -3 would cause this method to return
         * "XYZ". Punctuation, numbers, whitespace and other non-letter characters
         * should be left unchanged. NOTE: For full credit you are REQUIRED to use a
         * StringBuilder to build the String in this method rather than using String
         * concatenation.
         *
         * @param input String to be encrypted
         * @param shift Amount to shift each character of input to the right
         * @return the encrypted String as outlined above
         */
        public static String shift(String input, int shift) {
                StringBuilder sb = new StringBuilder(input.length());
                int len, myA, idxA;
                char c, coded = '\u0000';

                for (int i = 0; i < input.length(); i++) {
                        c = input.charAt(i);
                        if (Character.isLetter(c)) {
                                if (Character.isLowerCase(c)) {
                                        len = LOWERCASE.length();
                                        myA = LOWERCASE.indexOf(c);
                                        idxA = myA + shift;
                                        if (idxA >= len)
                                                idxA = idxA - 26;
                                        else if (idxA < 0)
                                                idxA = idxA + 26;

                                        coded = LOWERCASE.charAt(idxA);
                                } else if (Character.isUpperCase(c)) {
                                        len = UPPERCASE.length();
                                        myA = UPPERCASE.indexOf(c);
                                        idxA = myA + shift;
                                        if (idxA >= len)
                                                idxA = idxA - 26;
                                        else if (idxA < 0)
                                                idxA = idxA + 26;

                                        coded = UPPERCASE.charAt(idxA);
                                }
                        } else
                                coded = c;
                        sb.append(coded + "");

                }
                return (sb.toString());
        }

        /**
         * Displays the message "promptMsg" to the user and reads the next full line
         * that the user enters. If the user enters an empty string, reports the error
         * message "ERROR! Empty Input Not Allowed!" and then loops, repeatedly
         * prompting them with "promptMsg" to enter a new string until the user enters a
         * non-empty String
         *
         * @param in        Scanner to read user input from
         * @param promptMsg Message to display to user to prompt them for input
         * @return the String entered by the user
         */
        public static String promptForString(Scanner in, String promptMsg) {
                boolean done = false;
                do {
                        System.out.println(promptMsg);
                        String str = in.next();
                        if (str.length() > 0) {
                                done = true;
                                return str;
                        } else
                                System.out.println("ERROR! Empty Input Not Allowed!");
                } while (done == false);
                return null;
        }

        public static boolean transformFile(String inFile, String outFile, int shift) {
                try {
                        File file = new File(inFile);
                        Scanner sc = new Scanner(file);
                        BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));

                        while (sc.hasNextLine()) {
                                String shiftedstr = shift(sc.nextLine(), shift);
                                writer.write(shiftedstr);
                                writer.newLine();
                        }
                        System.out.println("Finished writing to file.");
                        sc.close();
                        writer.close();

                } catch (FileNotFoundException ex) {
                        System.out.println("Input/Output file is not found !! ");
                } catch (IOException ex) {
                        System.out.println("Input/Output file is not found !! ");
                }
                return true;

        }

        /**
         * Prompts the user to enter a single character choice. The only allowable
         * values are 'E', 'D' or 'Q'. All other values are invalid, including all
         * values longer than one character in length, however the user is allowed to
         * enter values in either lower or upper case. If the user enters an invalid
         * value, the method displays the error message "ERROR! Enter a valid value!"
         * and then prompts the user repeatedly until a valid value is entered. Returns
         * a single uppercase character representing the user's choice.
         *
         * @param in Scanner to read user choices from
         * @return the user's choice as an uppercase character
         */
        public static char getChoice(Scanner in) {
                boolean done = false;
                String s = in.next();
                do {
                        if (s.length() > 1)
                                System.out.println("ERROR! Enter a valid value!");
                        else {
                                char c = s.charAt(0);
                                char cupper = Character.toUpperCase(c);
                                if (cupper == 'E' || cupper == 'D' || cupper == 'Q') {
                                        done = true;
                                        return cupper;
                                } else
                                        System.out.println("ERROR! Enter a valid value!");
                        }
                        s = in.next();
                } while (done == false);
                return 0;
        }

        public static void displayMenu() {
                System.out.println("[E]ncode a file");
                System.out.println("[D]ecode a file");
                System.out.println("[Q]uit");
        }

        public static void main(String[] args) {

                Scanner in = new Scanner(System.in);
                displayMenu();

                System.out.println("Enter your choice :: ");
                char choice = getChoice(in);
                
                do {
                        String inFile;
                        String outFile;
                        int shift;
        
                        if (choice == 'E') {
                                inFile = promptForString(in, "Enter an input file :: ");
                                outFile = promptForString(in, "Enter an output file :: ");
                                shift = Integer.parseInt(promptForString(in, "Enter a shift amount :: "));
                                transformFile(inFile, outFile, shift);
                        } else if (choice == 'D') {
                                inFile = promptForString(in, "Enter an input file :: ");
                                outFile = promptForString(in, "Enter an output file :: ");
                                shift = Integer.parseInt(promptForString(in, "Enter a shift amount :: "));
                                transformFile(inFile, outFile, shift * -1);
                        } else if (choice == 'Q') {
                                System.out.println("Goodbye!");
                                break;
                        }
                        
                        if(choice != 'Q') {
                                System.out.println("Enter your choice :: ");
                                choice = getChoice(in);
                        }
                } while(true);

                in.close();
        }

}

Please upvote, as i have given the exact answer as asked in question. Still in case of any issues in code, let me know in comments. Thanks!

Add a comment
Know the answer?
Add Answer to:
You will be writing a simple Java program that implements an ancient form of encryption known...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • For this lab you will write a Java program that plays a simple Guess The Word...

    For this lab you will write a Java program that plays a simple Guess The Word game. The program will prompt the user to enter the name of a file containing a list of words. These words mustbe stored in an ArrayList, and the program will not know how many words are in the file before it starts putting them in the list. When all of the words have been read from the file, the program randomly chooses one word...

  • JAVA Problem: With the recent news about data breaches and different organizations having their clients’ information...

    JAVA Problem: With the recent news about data breaches and different organizations having their clients’ information being exposed, it is becoming more and more important to find ways to protect our sensitive data. In this program we will develop a simple tool that helps users generate strong passwords, encrypt and decrypt data using some cyphering techniques. You will need to create two classes. The first class is your driver for the application and contains the main method. Name this class...

  • For this lab you will write a Java program that plays the dice game High-Low. In...

    For this lab you will write a Java program that plays the dice game High-Low. In this game a player places a bet on whether the sum of two dice will come up High (totaling 8 or higher), Low (totaling 6 or less) or Sevens (totaling exactly 7). If the player wins, they receive a payout based on the schedule given in the table below: Choice Payout ------ ------ High 1 x Wager Low 1 x Wager Sevens 4 x...

  • Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains...

    Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains a Java program. Your program should read the file (e.g., InputFile.java) and output its contents properly indented to ProgramName_Formatted.java (e.g., InputFile_Formatted.java). (Note: It will be up to the user to change the name appropriately for compilation later.) When you see a left-brace character ({) in the file, increase your indentation level by NUM_SPACES spaces. When you see a right-brace character (}), decrease your indentation...

  • Python program Use the provided shift function to create a caesar cipher program. Your program s...

    python program Use the provided shift function to create a caesar cipher program. Your program should have a menu to offer the following options: Read a file as current message Save current message Type in a new message Display current message "Encrypt" message Change the shift value For more details, see the comments in the provided code. NO GLOBAL VARIABLES! Complete the program found in assignment.py. You may not change any provided code. You may only complete the sections labeled:#YOUR...

  • create a Java class ShiftCipher The program ShiftCipher should take two inputs from the terminal. The...

    create a Java class ShiftCipher The program ShiftCipher should take two inputs from the terminal. The first should be a string of any length which contains any type of symbol (the plaintext). The second will be a shift value which should be between 0 and 25 inclusive (though you may design your program to be resilient to shifts beyond this value). The program should print the cipher text, in which each of the alphabetic characters in the string is shifted...

  • Java Program Note: no break statements or switch staements High, Low, Sevens For this lab you...

    Java Program Note: no break statements or switch staements High, Low, Sevens For this lab you will write a Java program that plays the dice game High-Low. In this game a player places a bet on whether the sum of two dice will come up High (totaling 8 or higher), Low (totaling 6 or less) or Sevens (totaling exactly 7). If the player wins, they receive a payout based on the schedule given in the table below: Choice Payout ------...

  • JAVA Code: Complete the program that reads from a text file and counts the occurrence of...

    JAVA Code: Complete the program that reads from a text file and counts the occurrence of each letter of the English alphabet. The given code already opens a specified text file and reads in the text one line at a time to a temporary String. Your task is to go through that String and count the occurrence of the letters and then print out the final tally of each letter (i.e., how many 'a's?, how many 'b's?, etc.) You can...

  • Create a method based program to find if a number is prime and then print all...

    Create a method based program to find if a number is prime and then print all the prime numbers from 1 through 500 Method Name: isPrime(int num) and returns a boolean Use for loop to capture all the prime numbers (1 through 500) Create a file to add the list of prime numbers Working Files: public class IsPrimeMethod {    public static void main(String[] args)    {       String input;        // To hold keyboard input       String message;      // Message...

  • Given java code is below, please use it! import java.util.Scanner; public class LA2a {      ...

    Given java code is below, please use it! import java.util.Scanner; public class LA2a {       /**    * Number of digits in a valid value sequence    */    public static final int SEQ_DIGITS = 10;       /**    * Error for an invalid sequence    * (not correct number of characters    * or not made only of digits)    */    public static final String ERR_SEQ = "Invalid sequence";       /**    * Error for...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT