Assignemnt Project #5 and Caesar Cipher
Code
///Name: Daniel Tiffany-Appleton
///Period: 7
///Program Name: Caesar Cipher
///File Name: CaesarCipher
///Date Finished: 4/12/16
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class CaesarCipher
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
PrintWriter fileOut;
String plainText, cipher ="", choice, fileName, fileNaming;
int shift;
System.out.print("Which file has your message? ");
fileName = input.nextLine();
Scanner fileIn = new Scanner(new File(fileName));
plainText = fileIn.nextLine();
fileIn.close();
System.out.print("Want to encrypt or decrypt a message? ");
choice = input.nextLine();
if(choice.equals("encrypt"))
{
System.out.print("Shift (0 - 26): ");
shift = input.nextInt();
for(int i = 0; i < plainText.length(); i++)
{
cipher += shiftLetter(plainText.charAt(i), shift, choice);
}
}
else if(choice.equals("decrypt"))
{
System.out.print("Shift (0 - 26): ");
shift = input.nextInt();
for(int i = 0; i < plainText.length(); i++)
{
cipher += shiftLetter(plainText.charAt(i), shift, choice);
}
}
System.out.print("What do you want to call your message? ");
fileNaming = input.next();
fileOut = new PrintWriter(new File(fileNaming));
fileOut.println( cipher );
fileOut.close();
}
public static char shiftLetter(char c, int n, String choice)
{
int u = c;
if(!Character.isLetter(c))
return c;
if(choice.equals("encrypt"))
{
u = u + n;
}
else if(choice.equals("decrypt"))
{
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;
}
}
Picture of the output