1. 程式人生 > >Java 課堂作業 加密與解密

Java 課堂作業 加密與解密

源代碼 main nextline 流程 選擇 rgs mage put ext

1.設計思路

首先根據提示輸入一段字符串

利用charAt()將字符串的每個字符分解出來,要加密的話轉換成int類型後加3,解密的話轉換成int類型後減3,然後再轉化為char類型

新定義一個字符串變量,將轉換後的char鏈接起來輸出

2.流程圖

技術分享

3.源代碼

package test;
import java.util.Scanner;
class Cipher
{
Scanner input=new Scanner(System.in);
void incipher()
{
System.out.println("請輸入你想要加密的字符串:");
String str=input.nextLine();
String str2="";
for(int i=0;i<str.length();i++)
{
int n=(int)str.charAt(i)+3;
str2=str2+(char)n;
}
System.out.println("加密後的字符串為:"+str2);
}
void outcipher()
{
System.out.println("請輸入你想要解密的字符串:");
String str=input.nextLine();
String str2="";
for(int i=0;i<str.length();i++)
{
int n=(int)str.charAt(i)-3;
str2=str2+(char)n;
}
System.out.println("解密後的字符串為:"+str2);
}
}
public class Classtest5
{
public static void main(String[] args)
{
Cipher c=new Cipher();
Scanner input=new Scanner(System.in);
int choice;
do
{
System.out.println("請選擇你想要加密還是解密:1.加密 2.解密");
int choise=input.nextInt();
if(choise==1)
{
c.incipher();
}
else if(choise==2)
{
c.outcipher();
}
else
System.out.println("輸入錯誤!");
System.out.println("是否繼續?1.是 2.否");
choice=input.nextInt();
}while(choice==1);

}

}

4.截圖

技術分享

Java 課堂作業 加密與解密