我正在尝试制作一个简单的程序来加密和解密用户输入的消息。问题是在控制台中一切正常,但是当我尝试使用 JOptionPane 时,我收到一条错误消息,指出我无法从 void 转换为字符串。encrypt 方法适用于 JOptionPane。它的解密方法有问题。下面是我的代码:
import javax.swing.JOptionPane;
public class Encrypt {
public static final int ALPHASIZE = 26;
public static final char[] alpha = { 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z' };
protected char[] encrypt = new char[ALPHASIZE];
protected char[] decrypt = new char[ALPHASIZE];
public Encrypt() {
for (int i = 0; i < ALPHASIZE; i++)
encrypt[i] = alpha[(i + 3) % ALPHASIZE];
for (int i = 0; i < ALPHASIZE; i++)
decrypt[encrypt[i] - 'A'] = alpha[i];
}
public String encryptMessage(String secret) {
char[] mess = secret.toCharArray();
for (int i = 0; i < mess.length; i++)
if (Character.isUpperCase(mess[i]))
mess[i] = encrypt[mess[i] - 'A'];
return new String(mess);
}
public String decryptMessage(String secret) {
char[] mess = secret.toCharArray();
for (int i = 0; i < mess.length; i++)
if (Character.isUpperCase(mess[i]))
mess[i] = decrypt[mess[i] - 'A'];
return new String(mess);
}
public static void main(String[] args) {
Encrypt e = new Encrypt();
// String secret = "THIS IS THE SECRET MESSAGE";
// secret = e.encryptMessage(secret);
// System.out.println("Encrypted: " + secret);
// secret = e.decryptMessage(secret);
// System.out.println("Decrypted: " + secret);
String secret = JOptionPane.showInputDialog(null,"Enter message to be encrypted");
JOptionPane.showMessageDialog(null, e.encryptMessage(secret));
// this is where the problem is
String userInput = JOptionPane.showInputDialog(null, "Do you want to convert the message? (Y/N)");
if(userInput.equalsIgnoreCase("Y"))
secret = JOptionPane.showMessageDialog(null, e.decryptMessage(secret)));
}
}