/**
* Write in a message and run a Caesar cipher on it to encrypt the message
*
* @author Sameer, Raunaq, Schuyler
* @version 1.0
*/
import java.util.*;
public class CaesarCipher
{
public static void main (String args[]) {
//Initializing the alphabet variable
String alphabet = "abcdefghijklmnopqrstuvwxyz";
//While loop that runs continously to let you input message
while (true) {
//Initialize Scanner variable
Scanner sc = new Scanner(System.in);
//Enter shift as input
System.out.println("Please enter the shift:");
int shift = sc.nextInt();
//Initialize second Scanner variable
Scanner sc2 = new Scanner(System.in);
//Enter decrypted message as input
System.out.println("Please enter your decrypted message: ");
String input = sc2.nextLine();
input = input.toLowerCase();
//Loop to iterate through characters of a string
int first = 0;
int second = 1;
String finalString = "";
while (first < input.length()) {
//Take the character of the input
String character = input.substring(first, second);
int realIndex = alphabet.indexOf(character);
//Add the shift and take the new character from alphabet
int newIndex = realIndex + shift;
if (newIndex >= alphabet.length()) {
newIndex = alphabet.length() - newIndex;
}
String newChar = alphabet.substring(newIndex, (newIndex + 1));
finalString += newChar;
//Let loop keep running
first += 1;
second += 1;
}
//Print out final result
System.out.println(finalString);
}
}
}
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.