課後作業1:字串加密

我命傾塵發表於2017-10-26

1、古羅馬皇帝凱撒在打仗時曾經使用過以下方法加密軍事情報:

   

  請編寫一個程式,使用上述演算法加密或解密使用者輸入的英文字串要求設計思想、程式流程圖、原始碼、結果截圖

  設計思想:使用者從彈出的輸入訊息框內輸入字串,不限制大小寫。

  使用toCharArray()函式將字串轉化成字元陣列,再由加密和解密兩個按鈕分別對字元陣列的每個字元進行單獨操作,加密則+3,解密則-3。再強制轉換回字元型別並拼合成字串,從不可編輯的文字框輸出。

  程式流程圖:

   

  程式原始碼:

 1 package tiaoshi;
 2 import java.awt.*;
 3 import java.awt.event.*;
 4 import javax.swing.*;
 5 public class Test 
 6 {
 7     JFrame frame;
 8     JButton button1;
 9     JButton button2;
10     JTextArea text;
11     JScrollPane s;
12     public static void main(String[] args) 
13     {
14         Test g=new Test();
15         g.go();
16     }
17     public void go()
18     {
19         frame=new JFrame("密碼改寫");
20         button1=new JButton("加密");
21         button2=new JButton("解密");
22         text=new JTextArea();
23         s=new JScrollPane(text);
24         Container cp=frame.getContentPane();
25         cp.setLayout(null);
26         cp.add(button1);
27         cp.add(button2);
28         cp.add(s);
29         button1.setBounds(40,35,70,30);
30         button2.setBounds(190,35,70,30);
31         s.setBounds(20,100,260,60);
32         text.setEditable(false);
33         frame.setResizable(false);
34         frame.setSize(300,200);
35         frame.setVisible(true);
36         button1.addActionListener(new ActionListener()
37         {
38             public void actionPerformed(ActionEvent e)
39             {
40                     String s1=JOptionPane.showInputDialog(frame,"加密");
41                     char c[];
42                     c=s1.toCharArray();
43                     s1="";
44                     for(int i=0;i<c.length;i++)
45                     {
46                         if(c[i]==89||c[i]==90||c[i]==88||c[i]==120||c[i]==121||c[i]==122)
47                         c[i]=(char)(c[i]-23);
48                         else
49                         c[i]=(char) (c[i]+3);
50                         s1+=c[i];
51                     }
52                     text.setText(s1);
53             }
54          });
55         button2.addActionListener(new ActionListener()
56         {
57             public void actionPerformed(ActionEvent e)
58             {
59                  String s1=JOptionPane.showInputDialog(frame,"解密");
60                  char c[];
61                  c=s1.toCharArray();
62                  s1="";
63                  for(int i=0;i<c.length;i++)
64                  {
65                      if(c[i]==65||c[i]==66||c[i]==67||c[i]==97||c[i]==98||c[i]==99)
66                      c[i]=(char)(c[i]+23);
67                      else
68                      c[i]=(char) (c[i]-3);
69                      s1+=c[i];
70                  }
71                  text.setText(s1);
72              }
73           });
74     }
75 }

  結果截圖:

  初始介面:

   

  加密過程:

   

   

  解密過程:

  

   

相關文章