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

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);
}
}





One response to “Caesar Cipher (Java)”
[…] https://geektechstuff.com/2019/06/11/caesar-cipher-java/ […]
LikeLike