Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        6年前关闭。
                    
                
        

我正在做返回类型函数来加密一些字符串

我的代码是

public String encrypt(char x)
{
    String enc = "";
    switch(x)
    {
        case 'A' : enc = "B";
        break;
        case 'a' : enc = "x";
        break;
        case 'B' : enc = "C";
        break;
        case 'b' : enc = "w";
        break;
        case 'C' : enc = "D";
        break;
        case 'c' : enc = "v";
        break;
        case 'D' : enc = "E";
        break;
        case 'd' : enc = "u";
        break;
        case 'E' : enc = "F";
        break;
        case 'e' : enc = "t";
        break;
        case 'F' : enc = "G";
        break;
        case 'f' : enc = "s";
        break;
    }
    return(enc);
}

public String encryptString(String input)
{
    String Encryption = "";
    int length = input.length();
    int charVal = 0;
    for (charVal = 0; charVal<=length;charVal++)
    {
        char encChar = input.charAt(charVal);
        String encrypted = encrypt(encChar);
        Encryption = Encryption+encrypted+"";
    }
    return (Encryption);
}


我无法将encryptString()与JOptionPane的showInputDialog()一起使用。

最佳答案

for (charVal = 0; charVal<=length;charVal++)


应该

for (charVal = 0; charVal<length;charVal++)

否则,input.charAt(charVal);将在最后一次迭代中抛出StringIndexOutOfBoundsException

但是您可以使用StringBuilder使代码更高效:

public String encryptString(String input){
        StringBuilder sb = new StringBuilder();
        for (char c : input.toCharArray())
            sb.append(encrypt(c));
        return sb.toString();
}


几点注意事项:


您的encrypt(char x)方法的返回类型可以是char
请注意,如果用户取消了输入,则JOptionPane.showInputDialog返回null

10-08 01:40