Created
February 27, 2013 15:42
-
-
Save abaroody/5048855 to your computer and use it in GitHub Desktop.
Caesar Cipher in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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