凱撒加密法:消息中每個字母換成向后三個字母的字母,例如,明文ATUL變成密文DWXO。
MainKaisa.java
1 import javax.swing.JFrame;
2
3 public class MainKaisa {
4
5 /**
6 * @param nonles
7 */
8 public static void main(String[] args) {
9 //實例化一個窗體
10 KaisaFrame kaisaFrame = new KaisaFrame();
11 kaisaFrame.setVisible(true);
12 kaisaFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13
14 }
15
16 }
Kaisa.java
1 mport java.awt.event.ActionEvent;
2 import java.awt.event.ActionListener;
3 import javax.swing.*;
4
5 public class KaisaFrame extends JFrame {
6
7 JLabel jlDackText = new JLabel();
8 JButton btnBrightText = new JButton();
9 JPasswordField jpf = new JPasswordField();
10 JTextField jtf2 = new JTextField();
11 char[] buf;
12
13
14 public KaisaFrame() {
15 this.setSize(300,200); //設置窗體大小
16 this.setTitle("凱撒加密法");
17 this.setResizable(false);
18
19 jbInit();
20 }
21
22 private void isLetter() {
23 //判斷輸入的內容是否為字母
24 buf = jpf.getPassword();
25 for(char c:buf) {
26 if(Character.isLetter(c) == false) {
27 JOptionPane.showMessageDialog(this, "不能為非字符", "Error", JOptionPane.ERROR_MESSAGE);
28 jpf.setText("");
29 jtf2.setText("");
30 return;
31 } else {
32 makeBrightText();
33 }
34 }
35 }
36
37 private void makeBrightText() {
38 // 產生明文
39 char[] arr = new char[buf.length];
40 int index=0,temp;
41 for(char c:buf) {
42 temp = c+3; //字母后移三位
43 if( (temp>90 && temp<97) || temp>122 ) {
44 //若ASCII碼在此區間則減去26(使字符XYZ,xyz循環到XAB,xab)
45 temp = temp - 26;
46 arr[index++] = (char)temp;
47 } else {
48 arr[index++] = (char)temp;
49 }
50 }
51
52 String str = new String(arr);
53 jtf2.setText(str);
54
55 }
56
57 private void jbInit() {
58 // 設置窗體內容
59 this.setLayout(null);
60 jlDackText.setText("輸入密文:");
61 jlDackText.setBounds(30, 20, 80, 30);
62 btnBrightText.setText("生成明文:");
63 btnBrightText.setBounds(30, 90, 100, 30);
64 jpf.setBounds(160, 20, 80, 30);
65 jpf.setEchoChar('*');
66 jtf2.setBounds(160, 90, 80, 30);
67 jtf2.setEditable(false);
68
69 this.add(jlDackText);
70 this.add(jpf);
71 this.add(btnBrightText);
72 this.add(jtf2);
73
74 btnBrightText.addActionListener(new ActionListener(){
75
76 @Override
77 public void actionPerformed(ActionEvent e) {
78 isLetter(); //判斷輸入的內容是否為字母
79 }
80
81 });
82 }
83
84 }
85
現實圖解:
往文本框中輸入密文(只限字符),點擊按鈕,即生成相應密文。
若輸入為非字符,則彈出錯誤框~
簡單的一個程序,說明都不用了。。。