Project #5 and Caesar Cipher
Code
/// Name: Lauren Baird
/// Period: 7
/// Program Name: Caesar Cipher
/// File Name: P5.java
/// Date Finished: 3/31/2016
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.Scanner;
public class P5
{
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
{
System.out.println();
Scanner input = new Scanner(System.in);
String plainText, x, name, message, answer, cipher ="";
int shift;
System.out.print( "Would you like to encrypt or decrypt a message? " );
answer = input.nextLine();
System.out.print( "Where is the message located? " );
message = input.nextLine();
System.out.print( "What would you like to call your " + answer + "ed message? " );
String newFile = input.nextLine();
System.out.print("Shift (0 - 26): " );
shift = input.nextInt();
System.out.println();
Scanner fileIn = new Scanner(new File(message));
while (fileIn.hasNext())
{
x = fileIn.nextLine();
if (answer.equals("encrypt"))
{
for(int i = 0; i < x.length(); i++)
{
cipher += shiftLetter(x.charAt(i), shift);
}
}
else if (answer.equals("decrypt"))
{
shift = -1 * shift;
for(int i = 0; i < x.length(); i++)
{
cipher += shiftLetter(x.charAt(i), shift);
}
}
}
fileIn.close();
System.out.println( "Your " + answer + "ed message: " + cipher );
System.out.println();
PrintWriter fileOut;
try
{
fileOut = new PrintWriter( newFile + ".txt" );
}
catch(IOException e)
{
System.out.println( "There has been an error in opening " + newFile + ".txt " );
fileOut = null;
System.exit(1);
}
fileOut.println(cipher);
fileOut.close();
System.out.println( "Your " + answer + "ed message has been stored in " + newFile + ".txt " );
}
}