0

我正在尝试制作一个简单的程序来加密和解密用户输入的消息。问题是在控制台中一切正常,但是当我尝试使用 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)));
    }
}
4

2 回答 2

1

您正在使用 3 个重载 方法之一,它们都返回,即什么也没有。看起来您只想显示解密的消息,因此您不希望返回任何内容。就像在您的控制台尝试中一样,您没有将结果分配给任何东西,因此您不应该对.showMessageDialog voidSystem.out.printlnJOptionPane

删除作业。改变

secret = JOptionPane.showMessageDialog(null, e.decryptMessage(secret)));

JOptionPane.showMessageDialog(null, e.decryptMessage(secret));
于 2013-11-12T20:52:34.610 回答
0

除了 rgettman 的回答,如果您确实想将值存储在 中secret,我建议这样做:

secret = e.decryptMessage(secret);
JOptionPane.showMessageDialog(null, secret);
于 2013-11-12T20:54:51.847 回答