owen95
owen95

Reputation: 13

Encrypting using Caesar Cipher

Is there anyway to change this code so it will only encrypt uppercase letters? I don't need to it do lowercase or symbols. Thanks!

public class CaesarCypher
{
    public static final int MOVE_DOWN = 4;
    public static void main(String [] args)
    {

        String plainText;
        char character;

        System.out.println("Enter sentence or word to Encrypt: ");
        plainText = Console.readString();

        for ( int iteration = 0 ; iteration < plainText.length() ; iteration++ ) 
        {
            character = plainText.charAt( iteration );
            if ( character != ' ' ) 
            {
                character = (char) ( 'a' + ( character - 'a' + MOVE_DOWN ) %26 );
            }

            System.out.print(character);
        }


    }
}

Upvotes: 0

Views: 377

Answers (1)

Matthew V Carey
Matthew V Carey

Reputation: 316

Just replace the test for not a space with a test for upper case letters and the 'a' with an 'A'.

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CaesarCypher {

    public static final int MOVE_DOWN = 4;
    public static void main(String [] args)
    {

       String plainText = "";
       char character;

       System.out.println("Enter sentence or word to Encrypt: ");
       InputStreamReader converter = new InputStreamReader(System.in);
       BufferedReader in = new BufferedReader(converter);
       try{
           plainText = in.readLine();

           for ( int iteration = 0 ; iteration < plainText.length() ; iteration++ ) 
           {
               character = plainText.charAt( iteration );
               if ( character >='A' && character <= 'Z' ) 
               {
                   character = (char) ( 'A' + ( character - 'A' + MOVE_DOWN ) %26 );
               }

               System.out.print(character);
           }
       }
       catch (Exception e){
           System.err.println(e.getMessage());
       }

    }
}

Upvotes: 1

Related Questions