使用Caesar Cipher加密

时间:2014-11-26 23:21:22

标签: java encryption

有没有改变这个代码所以它只会加密大写字母?我不需要它做小写或符号。谢谢!

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);
        }


    }
}

1 个答案:

答案 0 :(得分:1)

只需用大写字母测试替换不是空格的测试,用'A'替换​​'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());
       }

    }
}