Project #5 Caesar Cipher
Code
Name: Iaroslav Titov
Period: 7
Project Name: CaesarCipher
File Name: CaesarCipher.java
Date: 3/16/2015
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
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)
{
System.out.println("\n Welcome to the CipherCreator by TIS!!!\n");
boolean mode = getMode();
File input = getFile(true);
Scanner fileIn = new Scanner(System.in);
try
{
fileIn = new Scanner(input);
}
catch(IOException e){System.out.println("FILE NOT FOUND");}
File output = getFile(false);
int shift = getShift() * (mode? 1:-1);
String plainText = "";
String cipher = "";
while (fileIn.hasNext())
{
plainText += fileIn.nextLine();
plainText +="\n";
}
for(int i = 0; i < plainText.length(); i++)
{
cipher += shiftLetter(plainText.charAt(i), shift);
}
fileIn.close();
outputToFile(cipher, output.getName());
System.out.print("\n Output successful!\n >");
}
public static void outputToFile(String cipher, String name)
{
PrintWriter fileOut = null;
while (fileOut==null)
{
try {
fileOut = new PrintWriter(name);
} catch(Exception e){System.out.println("OUTPUT FILE NOT FOUND");}
}
fileOut.print(cipher);
fileOut.close();
}
public static boolean getMode()
{
Scanner in = new Scanner(System.in);
String read = "";
while (!(read.equals("encrypt") || read.equals("decrypt")) )
{
System.out.print(" Do you want to encrypt or decrypt?\n >");
try
{
read = in.nextLine();
}
catch (InputMismatchException e)
{
System.out.print("\n"+read+" is not an accepted command.\n");
read = "";
}
}
if (read.equals("encrypt")) return true;
else return false;
}
public static int getShift()
{
Scanner input = new Scanner(System.in);
int shift = 0;
while (shift==0)
{
System.out.print("\n What is the shift?\n > ");
try
{
shift = input.nextInt();
}
catch (InputMismatchException e){shift = 0;};
}
return shift;
}
public static File getFile(boolean input)
{
Scanner in = new Scanner(System.in);
File file = null;
boolean good = false;
while (!good)
{
try
{
if (input) System.out.print("\n Put in source file name\n >");
else System.out.print("\n Put in output file name\n >");
file = new File(in.nextLine());
if(file.exists() && !file.isDirectory()) good = true;
else
{
good = false;
System.out.print("\n File does not exist!!!\n");
}
}
catch (Exception e)
{
file = null;
}
}
return file;
}
}
Picture of the output