Project Number 5 and Caesar Cipher
Code
/// Name: Brendan Baird
/// Period: 6
/// Program Name: Caesar Cipher
/// File Name: CaesarCipher.java
/// Date Finished: 5/9/2016
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class CaesarCipher {
public static char shiftLetter(char c, int n) {
int u = c;
if(!Character.isLetter(c))
return c;
u = u + n;
if(Character.isUpperCase(c) && u > 'Z' || Character.isLowerCase(c) && u > 'z') {
u -= 26;
}
if(Character.isUpperCase(c) && u < 'A' || Character.isLowerCase(c) && u < 'a') {
u += 26;
}
return (char)u;
}
public static void main(String[] args) throws Exception {
PrintWriter fileOut;
Scanner input = new Scanner(System.in);
String file1, file2, cipher = "";
int shift;
System.out.print("\nWould you like to encrypt or decrypt a message? ");
String cryptChoice = input.next();
System.out.print("\nWhich file would you like to choose: ");
file1 = input.next();
System.out.println();
System.out.print("Shift (0 - 26): ");
shift = input.nextInt();
Scanner fileReader = new Scanner(new File(file1));
System.out.println("Message:\n");
while(fileReader.hasNext()){
String line = fileReader.nextLine();
System.out.println(line); //prints chosen message to console
if (cryptChoice.equals("Decrypt") || cryptChoice.equals("decrypt")){
shift = -1 * shift;
}
for(int i = 0; i < line.length(); i++) {
cipher += shiftLetter(line.charAt(i), shift);
} //shifts message by a number of characters depending on decryption or encryption
}
fileReader.close();
System.out.println("\n" + cipher);
System.out.print("What should the name of the message be? ");
file2 = input.next();
try{
fileOut = new PrintWriter(file2 + ".txt");
} catch(IOException e) {
System.out.println("Sorry, I can't open the file.");
fileOut = null;
System.exit(1);
}
fileOut.println(cipher);
fileOut.close();
}
}
Picture of the output