2014-01-06 78 views
0

我正在返回類型函數加密一些字符串功能在java中

我的代碼是

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()

+4

你是什麼意思,你不能使用該功能?它是否會拋出異常? – Hrishikesh

回答

2
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如果用戶取消輸入
+1

謝謝, 它的工作 –