凯撒的字符串加密

一、设计思想: 

  设计两个函数,一个用来加密,一个用来解密。首先使用charAt对字符串的每一个字符进行向后以三位的操作,注意分别大小写,为了避免超出范围,所以还需判断是否超出范围,超过z则减26,小于a加26;

二、程序流程图:

凯撒的字符串加密

三、源代码:

package StringEncryption;

import java.util.Scanner;

public class StringEncryption 
{

    public void Encryption(String s)//加密
    {
        String string="";
        for(int i=0;i<s.length();i++)
        {
            char c=s.charAt(i);
            if(c>='a'&&c<='z')
            {
                c+=3;
                if(c<'a') c+=26;
                if(c>'z') c-=26;
            }
            if(c>='A'&&c<='Z')
            {
                c+=3;
                if(c<'A') c+=26;
                if(c>'Z') c-=26;
            }
            string +=c;
        }
        System.out.println(string);
        
    }
    public void Decrypyion(String s)//解密
    {
        String string="";
        for(int i=0;i<s.length();i++)
        {
            char c=s.charAt(i);
            if(c>='a'&&c<='z')
            {
                c-=3;
                if(c<'a') c+=26;
                if(c>'z') c-=26;
            }
            if(c>='A'&&c<='Z')
            {
                c-=3;
                if(c<'A') c+=26;
                if(c>'Z') c-=26;
            }
            string +=c;
        }
        
        System.out.println(string);
    }
    public static void main(String[] args) 
    {
        StringEncryption strEn=new StringEncryption();
        Scanner cin=new Scanner(System.in);
        System.out.println("1、加密          2、解密");
        int a=cin.nextInt();
        
        if(a==1)
        {
            System.out.println("请输入原文:");
            cin.nextLine();
            String str=cin.nextLine();
            System.out.println("密文为:");
            strEn.Encryption(str);
        }
        else if(a==2)
        {
            System.out.println("请输入密文:");
            cin.nextLine();
            String str=cin.nextLine();
            System.out.println("原文为:");
            strEn.Decrypyion(str);
            
        }
        else System.out.println("操作错误,退出");
        cin.close();
    }
    
}

四、结果截图:

凯撒的字符串加密

凯撒的字符串加密