Project #5

Code

    /*
jack newsom
period 5
program CaesarCipher
filename CaesarCipher.java
date completed 2/23/2016
*/

import java.util.Scanner;
import java.io.File;

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 {

            Scanner input = new Scanner(System.in);
            String shiftedMessage = "", message;
            int shift;
            /*String plainText, cipher ="";
            int shift;

            System.out.print("Message to encrypt: ");
            plainText = input.nextLine();

            System.out.print("Shift (0 - 26): ");
            shift = input.nextInt();

            for(int i = 0; i < plainText.length(); i++) {
                cipher += shiftLetter(plainText.charAt(i), shift);
            }

            System.out.println(cipher);
            */


            System.out.println("Would you like to \"encrypt\" or \"decrypt\" a message?");
            String userChoice = input.nextLine();

            while ( userChoice.equals("encrypt") == false && userChoice.equals("decrypt") == false )
            {
                System.out.println("Whoops. I couldn't interpret your input. Try again.");
                System.out.println("Would you like to \"encrypt\" or \"decrypt\" a message?");
                userChoice = input.next();
            }

            System.out.println("Ok, what name of the file you'd like to " + userChoice + "?");
            String fileName = input.nextLine();
        
            System.out.println("Ok, please choose a shift factor between 0-26, inclusive:");
            shift = input.nextInt();
        
            Scanner fileReader = new Scanner(new File(fileName));
        
            if ( userChoice.equals("decrypt") == true )
            {
                shift = -1*shift;   
            }
        
            
            while ( fileReader.hasNext())
            {
                message = fileReader.nextLine();
                
                for ( int i = 0; i < message.length(); i++ )
                {
                       shiftedMessage += shiftLetter(message.charAt(i), shift);
                }

                System.out.println(shiftedMessage);
                shiftedMessage = "";
                
            }
            
        

        
        }
    
    
}

  
    

Picture of the output