Question

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 by the given amount, for example:

Input Shift Value Result
A 0 A
A 1 B
A 5 F
Z 1 A

Lower case letters should be shifted in the same manner (meaning that a lower case letter should remain lower case, and an upper case should remain upper case). All other characters (i.e. those that are not alphabetic) should remain unchanged. Print the resulting shifted string to the terminal.

For example, given the input:

Iacta alea est!
3

the program should print the output:

Ldfwd dohd hvw!

Hint - You may want to consider the relationship between strings, arrays and ASCII values.

Extension - Abstract your core shifting algorithm into a method/function which can accept positive or negative shift values. Now write a decode method which given a cipher text and a known shift value returns the string to its original form. Validate the relationship between your methods by ensuring that applying first the encode function and then the decode function (with the same shift) returns the original plaintext.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import jdk.swing.interop.SwingInterOpUtils;

class Main {
    public static String shift(String s, int shift) {
        //Variable to store ans
        String ans = "";
        //Loop through all chars in the string
        for (int i = 0; i < s.length(); i++) {
            //Current character
            char ch = s.charAt(i);
            //Modified new character
            int newchar = ch;
            //Check if char is lowercase or uppercase
            if (Character.isLowerCase(ch)) {
                //Shift the letter
                newchar = (int) ch + shift;
                //If char exceeds 'z' or 'a', then wrap it
                if (newchar > 'z') {
                    newchar = 'a' + (newchar - 'z' - 1)%26;
                } else if (newchar < 'a') {
                    newchar = 'z' - ('a' - newchar + 1)%26;
                }
            }
            else if(Character.isUpperCase(ch)){
                newchar = (int) ch + shift;
                if (newchar > 'Z') {
                    newchar = 'A' + (newchar - 'A' - 1)%26;
                } else if (newchar < 'A') {
                    newchar = 'Z' - ('A' - newchar + 1)%26;
                }
            }
            ans = ans + (char)newchar;
        }
        return ans;
    }


    public static void main(String[] args) {
        String s = "lacta alea est!";
        System.out.println("Original : "+s);
        String encrypted = shift(s,3);
        System.out.println("Encrypted : "+encrypted);
        String decrypted = shift(encrypted,-3);
        System.out.println("Decrypted : "+decrypted);
        System.out.println("Decrypted and original match? "+(decrypted.equals(s)));
    }
}

OUTPUT :

IVIU Run: Main X C:\Program Files\Java\jdk-13\bin\java.exe -javaagent: Original : lacta alea est! Encrypted : odfwd dohd h

Add a comment
Know the answer?
Add Answer to:
create a Java class ShiftCipher The program ShiftCipher should take two inputs from the terminal. The...
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
  • C Program In this assignment you'll write a program that encrypts the alphabetic letters in a...

    C Program In this assignment you'll write a program that encrypts the alphabetic letters in a file using the Vigenère cipher. Your program will take two command line parameters containing the names of the file storing the encryption key and the file to be encrypted. The program must generate output to the console (terminal) screen as specified below. Command Line Parameters Your program must compile and run from the command line. The program executable must be named “vigenere” (all lower...

  • using the website repl.it (must be done in Javascript) PGM #1 Write a Java program that can perform the Caesar cipher fo...

    using the website repl.it (must be done in Javascript) PGM #1 Write a Java program that can perform the Caesar cipher for English messages that include both upper and lowercase alphabetic characters. The Caesar cipher replaces each plaintext letter with a different one, by a fixed number of places down the alphabet. The cipher illustrated here uses a left shift of three, so that (for example) each occurrence of E in the plaintext becomes B in the ciphertext. For example...

  • Using the website Repl.it Write a Java program that can perform the Caesar cipher for English...

    Using the website Repl.it Write a Java program that can perform the Caesar cipher for English messages that include both upper and lowercase alphabetic characters. The Caesar cipher replaces each plaintext letter with a different one, by a fixed number of places down the alphabet. The program should be able to shift a specific number of places based on the user's input number. For example Plaintext: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. Ciphertext: QEBNRFZH YOLTK CLU GRJMP...

  • [Java] Create a class called FileExercises that contains the following method Method encrypt that does not...

    [Java] Create a class called FileExercises that contains the following method Method encrypt that does not return anything and takes a shift, input filename and output filename as arguments. It should read the input file as a text file and encrypt the content using a Caesar cypher with the shift provided. The resulting text should be placed in the output file specified. (If the output file already exists, replace the existing file with a new file that contains the required...

  • JAVA PROJECT Part 1 - Normalize Text The first thing we will do is normalize the...

    JAVA PROJECT Part 1 - Normalize Text The first thing we will do is normalize the input message so that it’s easier to work with. Write a method called normalizeText which does the following: Removes all the spaces from your text Remove any punctuation (. , : ; ’ ” ! ? ( ) ) Turn all lower-case letters into upper-case letters Return the result. The call normalizeText(“This is some \“really\” great. (Text)!?”) should return “THISISSOMEREALLYGREATTEXT” Part 2 - Obfuscation...

  • Using Python; Caesar part of the homework: Write c_encrypt() and c_decrypt(), both of which take two...

    Using Python; Caesar part of the homework: Write c_encrypt() and c_decrypt(), both of which take two arguments, the first one a string and the second one an integer key. Both should return a string. Vigenère part of the homework: Write vig_encrypt() and vig_decrypt() functions. Each takes two strings as inputs, with the first being the plaintext/ciphertext, and the second being the key. Both should be calling functions you wrote earlier to help make the work easier. The key will be...

  • 1. Write a C++ program called Password that handles encrypting a password. 2. The program must...

    1. Write a C++ program called Password that handles encrypting a password. 2. The program must perform encryption as follows: a. main method i. Ask the user for a password. ii. Sends the password to a boolean function called isValidPassword to check validity. 1. Returns true if password is at least 8 characters long 2. Returns false if it is not at least 8 characters long iii. If isValidPassword functions returns false 1. Print the following error message “The password...

  • 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...

  • Write a Java program which takes a string as a user input. Create 2 functions. The...

    Write a Java program which takes a string as a user input. Create 2 functions. The first function expects a string as argument and returns void. It converts all upper case characters to lower case and converts all lower case characters to upper case. It then prints out the converted string to a console. The second function also expects a string as argument and returns void. It will find first charactor that is repeated exactly 2 times in the string....

  • WE ARE USING PYTHON TO COMPLETE THIS ASSIGNMENT :) THANK YOU! In this programming assignment, you...

    WE ARE USING PYTHON TO COMPLETE THIS ASSIGNMENT :) THANK YOU! In this programming assignment, you will write functions to encrypt and decrypt messages using simple substitution ciphers. Your solution MUST include: a function called encode that takes two parameters: key, a 26-character long string that identifies the ciphertext mapping for each letter of the alphabet, in order; plaintext, a string of unspecified length that represents the message to be encoded. encode will return a string representing the ciphertext. a...

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