Skip to content

Instantly share code, notes, and snippets.

@abaroody
Created Feb 27, 2013
Embed
What would you like to do?
Caesar Cipher in Java
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
public class cipher
{
public static void main(String[]args)
throws java.io.IOException
{
FileReader ReadFile = new FileReader("input.txt");
BufferedReader ReadFileBuffer = new BufferedReader(ReadFile);
FileWriter WriteFile = new FileWriter("output.txt");
BufferedWriter WriteFileBuffer = new BufferedWriter(WriteFile);
ArrayList<String> inputArray = new ArrayList<String>();
String currentLine;
int lineCounter = 0;
while((currentLine = ReadFileBuffer.readLine()) != null)
{
inputArray.add(currentLine);
lineCounter++;
}
ReadFileBuffer.close();
Iterator<String> iter = inputArray.iterator();
while(iter.hasNext())
{
String line = iter.next().toUpperCase();
for(int i=0;i<line.length();i++)
WriteFileBuffer.write(cipherLetter(line.charAt(i), true));
WriteFileBuffer.write("\n");
}
WriteFileBuffer.close();
}
public static char cipherLetter(char letter, boolean encode)
{
int cipherLength = 3;
int ascii = (int)letter;
if (ascii>=65 && ascii<=90)
{
ascii += encode ? cipherLength : -cipherLength;
ascii = (ascii-65);
if (ascii < 0 ) ascii += 25;
ascii = ascii % 25 + 65;
}
return (char)ascii;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment