2013-07-30 25 views
-2

第一次來這裏。我試圖編寫一個程序,它接受來自用戶的字符串輸入並使用replaceFirst方法對其進行編碼。除「`」(格雷夫重音)以外的所有字母和符號都可以正確編碼和解碼。replaceFirst字符 「`」

例如當我輸入

`12 

我應該得到28AABB作爲我的加密,而是,它給了我BB8AA2

public class CryptoString { 


public static void main(String[] args) throws IOException, ArrayIndexOutOfBoundsException { 

    String input = ""; 

    input = JOptionPane.showInputDialog(null, "Enter the string to be encrypted"); 
    JOptionPane.showMessageDialog(null, "The message " + input + " was encrypted to be "+ encrypt(input)); 



public static String encrypt (String s){ 
    String encryptThis = s.toLowerCase(); 
    String encryptThistemp = encryptThis; 
    int encryptThislength = encryptThis.length(); 

    for (int i = 0; i < encryptThislength ; ++i){ 
     String test = encryptThistemp.substring(i, i + 1); 
     //Took out all code with regard to all cases OTHER than "`" "1" and "2" 
     //All other cases would have followed the same format, except with a different string replacement argument. 
     if (test.equals("`")){ 
      encryptThis = encryptThis.replaceFirst("`" , "28"); 
     } 
     else if (test.equals("1")){ 
      encryptThis = encryptThis.replaceFirst("1" , "AA"); 
     } 
     else if (test.equals("2")){ 
      encryptThis = encryptThis.replaceFirst("2" , "BB"); 
     } 
    } 
} 

我試圖把轉義字符的重音的前面,但是,它仍然沒有正確編碼。

+3

你真的有一個'else'沒有' if'? –

+2

你的代碼不能編譯。發佈您正在使用的真實代碼會更有幫助。 – Pshemo

+0

我刪除了所有其他情況,只顯示這個特定的情況。 – user2635709

回答

0

encryptThistemp.substring(i, i + 1);子的第二個參數是長度,你確定要被增加i?因爲這意味着在第一次迭代test後不會有1個字符長。這可能會甩掉我們看不到的其他情況

2

看看你的程序在每次循環迭代是如何工作的:

    • i=0
    • encryptThis = '12(我用'而不是'來更容易寫這個帖子)
    • 現在你替換'28,所以它會變成2812
    • i=1
    • 我們在位置1讀取的字符,這是1所以
    • 我們用AA製備2812替換1 - >28AA2
    • i=2
    • 我們在2位讀取的字符,它是如此2
    • 我們替換杉ST2BB使2812 - >BB8AA2

儘量使用可能從appendReplacementMatcherjava.util.regex包像

public static String encrypt(String s) { 
    Map<String, String> replacementMap = new HashMap<>(); 
    replacementMap.put("`", "28"); 
    replacementMap.put("1", "AA"); 
    replacementMap.put("2", "BB"); 

    Pattern p = Pattern.compile("[`12]"); //regex that will match ` or 1 or 2 
    Matcher m = p.matcher(s); 
    StringBuffer sb = new StringBuffer(); 

    while (m.find()){//we found one of `, 1, 2 
     m.appendReplacement(sb, replacementMap.get(m.group())); 
    } 
    m.appendTail(sb); 

    return sb.toString(); 
}