2014-12-05 142 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