Caesar Cipher (Java)

Java Caesar Cipher

One of the earlier programs I wrote in Python was a Caesar Cipher (later updating it to add a GUI). As part of my recent Java learning I have created a Caesar Cipher in Java. If you want to read more about Caesar Ciphers then please check out: https://en.wikipedia.org/wiki/Caesar_cipher

geektechstuff_java_caesar_cipher
Java Caesar Cipher

I have placed the Java file for this project (cipher.java) on my GitHub: https://github.com/geektechdude/Java_stuff

/* GeekTechStuff Caesar Cipher */

import java.util.Scanner;

public class cipher {

    public static void main(String[] args){
        System.out.print("Caesar Cipher Number: ");
        Scanner input = new Scanner(System.in);
        int cipherNumber = input.nextInt(); //takes user input
        System.out.println(replaceAlpha(cipherNumber)); //runs replaceAlpha which does the cipher work

    }

    public static String normalizeText(){
    /* Remove spaces and non-letters from text */
    System.out.print("Enter text to cipher: ");
    Scanner input = new Scanner(System.in);
    String userInput = input.nextLine(); //takes user input
    String inputUpper = userInput.toUpperCase(); //converts input to UPPER case
    String removeSpaces = inputUpper.replaceAll("\\s+",""); //removes any spaces
    String removeNonLetters = removeSpaces.replaceAll("[^a-zA-Z]",""); //removes any non-letter characters
    String normlizedText = removeNonLetters;
    return(normlizedText);
    }


    public static String replaceAlpha(int cipher_shift){
        String textToUse = normalizeText(); //runs normalizeText to take text input
        String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String newString ="";
        int lengthOfText = textToUse.length();
        for(int i=0;i<lengthOfText;i++){
            char letter = textToUse.charAt(i);
            int postition = letters.indexOf(i);
            char replacedLetters = letters.charAt(i+cipher_shift);
            newString = newString+replacedLetters;
            }
        return(newString);
    }

    }

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.