凱撒加密解密(java字母移位)


1.設計思想:加密就是將字符數據轉化為ASC碼表中的數字,a—w之間通過加3之后再轉化為字符型輸出,x—z之間通過轉化為ASC碼表中的數字后減去23再轉化為字符型輸出。解密就是將字符數據轉化為ASC碼表中的數字,d—z之間通過減去3之后再轉化為字符型輸出,a—c之間通過轉化為ASC碼表中的數字后加23再轉化為字符型輸出。

2.程序流程圖

3.程序源碼

import java.util.Scanner;
public class Code {
//嚴羽卿 凱撒加密與解密  2015 10 23
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String input = null;
  Scanner sc = new Scanner(System.in);
  System.out.println("請輸入字母:");
  input = sc.next();
  StringBuffer code = new StringBuffer();
        Scanner sc1=new Scanner(System.in);
  System.out.println("加密請按1,解密請按2:"); 
        int p;
        p=sc1.nextInt();     
        if(p==1)
        {
      System.out.println("加密之后為:");     
      for(int i = 0;i < input.length();i++)
      {
       char x = input.charAt(i);
       
       if(x >= 'a' && x <= 'w')
       {
        x = (char)(x+3);
        code.append(x);
       }
       if(x >= 'x' && x <= 'z')
       {
        x=(char)(x-23);
        code.append(x);
       }
       
       if(x >= 'A' && x <= 'W')
       {
        x = (char) (x+3);

        code.append(x);
       }
       if(x >= 'X' && x <= 'Z')
       {
        x=(char)(x-23);
        code.append(x);
       }

      } 
        }
        if(p==2)
        {
      System.out.println("解密:");
      for(int i = 0;i < input.length();i++)
      {
       char x = input.charAt(i);
       if(x >= 'a' && x <= 'c')
       {
        x=(char)(x+23);
        code.append(x);
       }
       else if(x >= 'd' && x <= 'z')
       {
        x = (char)(x-3);
        code.append(x);
       }
       else if(x >= 'A' && x <= 'C')
       {
        x=(char)(x+23);
        code.append(x);
       }
       
       else if(x >= 'D' && x <= 'Z')
       {
        x = (char) (x-3);

        code.append(x);
       }

      }
        }
  System.out.println(code);
 

 }

}

4.結果截圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM