/**
* Caesar Chipher Maker
* @author Josh Wang
* @version 09/14/17
*/
import java.util.*;
public class CaesarCipher{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String en = "";
String alpha = "abcdefghijklmnopqrstuvwxyz";
String Alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String num = "0123456789";
System.out.print("\nInput: ");
String in = sc.nextLine();
System.out.print("Shift (Max 2,147,483,647): ");
int shift = sc.nextInt();
for (int length = 0; length < in.length(); length++){ //loops for each character of in
int temp = alpha.indexOf(in.substring(length, length+1)); //temp is the nth letter of in
if (temp >= 0){ //if the nth character of in is a lower-case alpha, index returns >= 0
if ((temp + shift) % 26 < (temp + shift + 1) % 26){
en += alpha.substring((temp + shift) % 26, (temp + shift + 1) % 26);
}
else{//for when shift places substring directly on the transition from last to first character of string, causing out of range for substring
en += alpha.substring((temp + shift) % 26);
}
}
else{ //if nth character is not lower alpha
temp = Alpha.indexOf(in.substring(length, length+1));
if (temp >= 0){ //if nth character is upper-case alpha, temp >= 1, etc.
if ((temp + shift) % 26 < (temp + shift + 1) % 26){
en += Alpha.substring((temp + shift) % 26, (temp + shift + 1) % 26);
}
else{
en += Alpha.substring((temp + shift) % 26);
}
}
else{
temp = num.indexOf(in.substring(length, length+1));
if (temp >= 0){
if ((temp + shift) % 10 < (temp + shift + 1) % 10){
en += num.substring((temp + shift) % 10, (temp + shift + 1) % 10);
}
else{
en += num.substring((temp + shift) % 10);
}
}
else{ //if nth character is not alphanumerical, character remains the same
en += in.substring(length, length+1);
}
}
}
}
System.out.println("\n" + en);
}
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.