2014-12-05 140 views
0

我想使用遞歸技術來解壓字符串。我有一些工作,給我一些這樣異常線程「main」 java.lang.NumberFormatException錯誤代碼:對於輸入字符串:「」遞歸解壓縮字符串

例如,當我在一個字符串發送像4a4b4c或40A5B10c,它工作得很好。當使用字符串像「a9T3b5R6t3h2g4v5b4n」

這裏是我的代碼

public static void main(String[] args){ 
    System.out.println(uncompress("a9T3b5R6t3h2g4v5b4n")); 
} 

public static String uncompress(String Text){ 
    return uncompress(Text, "", ""); 
} 

public static String count(char ch, int n){ 
     if(n == 0){return "";} 
     return "" + ch + count(ch, n-1); 
    } 

public static String uncompress(String Text, String count, String output){ 
    if(Text.equals("")){ 
     return output; 
    } 
    if(Character.isLetter(Text.charAt(0))){ 
     output += count(Text.charAt(0), Integer.parseInt(count)); 
     count = ""; 
    } 
    else if(Character.isDigit(Text.charAt(0))){ 
     count += ("" + Text.charAt(0)); 
    } 


    return uncompress(Text.substring(1), count, output); 
} 
+1

什麼是'decompress'? – irrelephant 2014-12-05 06:03:56

+1

'decompress()'在哪裏?請告訴我們完整的相關源代碼。 – 2014-12-05 06:04:21

+0

@Abhi是否解壓縮方法?你的意思是解壓縮(文本,「」,「」); ? – Secondo 2014-12-05 06:06:46

回答

1

只是處理NumberFormatException(NFE),然後如果第一個輸入是一個字符串,然後保留它,可以選擇另一種解決方案。我不太清楚我的解釋是否可以改正。只是想幫忙。 TIA。

public static void main(String[] args){ 
    System.out.println(uncompress("abasd4a4b4c")); 
} 

public static String uncompress(String text){ 
    return uncompress(text, "", ""); 
} 

public static String count(char ch, int n){ 
     if(n == 0){return "";} 
     return "" + ch + count(ch, n-1); 
    } 

public static String uncompress(String text, String count, String output){ 
    if(text.equals("")){ 
     return output; 

    }else if(Character.isLetter(text.charAt(0))){ 
     try{ 
      output += count(text.charAt(0), Integer.parseInt(count)); 
     }catch(NumberFormatException nfe){ 
      output += text.charAt(0); 
     } 
     count = ""; 
    }else if(Character.isDigit(text.charAt(0))){ 
     count += ("" + text.charAt(0)); 
    } 
    return uncompress(text.substring(1), count, output); 
} 

輸出:

abasdaaaabbbbcccc 
+0

非常感謝你 – AP6 2014-12-05 17:29:51

+0

你的歡迎:) – Secondo 2014-12-08 00:10:51

1

我覺得你得到的異常java.lang.NumberFormatException,因爲如果字符串以字母開頭的代碼獲取到

的錯誤出現
if(Character.isLetter(Text.charAt(0))){ 
    newString += count(Text.charAt(0), Integer.parseInt(count)); 
    count = ""; 
} 

塊,並嘗試解析count哪個值""因爲第一解壓縮被稱爲與return uncompress(Text, "", "");

總之,該代碼只能處理以數字開頭的壓縮字符串。也許你可以先嚐試驗證輸入的壓縮字符串以避免異常。

+0

非常感謝你加入嘗試和趕上解決問題 – AP6 2014-12-05 17:28:11