我在想办法也无法在Java中解压缩String时遇到麻烦。这是我要学习的基本Java类,因此只需要基本命令,没有什么花哨的地方。它能够输入的目标
C:\>java Compress -c aaaabbbbbcc
在命令提示符下,它将打印a4b5c2(就像它压缩参数字符串一样)。
a4b5c2
另一个目标是输入
C:\>java Compress -d a5b7c4
它将打印aaaaabbbbbbbcccc(就像它将解压缩参数String一样)。减压是我遇到的问题。这是我的代码,非常感谢我得到的任何帮助。
aaaaabbbbbbbcccc
import java.util.*; public class Compress { public static void main(String args[]) { Scanner scan = new Scanner(System.in); String originalString = scan.nextLine(); int number = scan.nextInt(); if (args[0].equals("-c")) { System.out.println("compress"); compress(originalString); } else if (args[0].equals("-d")) { System.out.println("decompress"); decompress(originalString); } else { System.out.println("Compress program by Kelsey Faram"); System.out.println("usage: java Compress [-c,-d] < inputFile > outputFile"); } } public static void compress(String originalString) { int count = 0; char comp = originalString.charAt(0); for (int i = 0; i < originalString.length(); i++) { originalString.charAt(i); if (comp == originalString.charAt(i)) count++; else { System.out.print(comp + "" + count); comp = originalString.charAt(i); count = 1; } } System.out.println(comp + "" + count); } public static void decompress(String originalString) { } }
Quick Code for you..
public static void decompress(String originalString) { StringBuffer finalString = new StringBuffer();; char previouschar = originalString.charAt(0); for(int i=1; i < originalString.length(); i+=2){ for(int j = 0 ; j< Integer.parseInt(""+originalString.charAt(i));j++) { finalString.append(previouschar); } if(i+1 < originalString.length()) { previouschar=originalString.charAt(i+1); } } System.out.println(finalString.toString()); }