我需要这段代码来压缩和解压缩用户给定的字符串,要压缩用户将键入“java compression -c”或只是“java compression”。要解压缩,它将是“java压缩-d”。任何帮助,将不胜感激。它现在将编译并运行;但是,当您输入字符串时,它只会打印出 compress 而不是压缩的字符串。
import java.util.*;
public class practice
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
String originalString = scan.nextLine();
String compressedString = "";
int index = 0;
int numReps = 0;
char nextChar = ' ';
if (args.length==0 || args[0].equals("-c"))
{
System.out.println("compress");
String s = scan.next();
compress(originalString);
System.out.println(compressedString);
}
else if (args[0].equals("-d"))
{
System.out.println("decompress");
decompress(compressedString);
}
else
{
System.out.println("Error! Unknown mode.");
}
}
public static void compress(String originalString)
{
int index = 0;
int numReps = 0;
char nextChar = ' ';
while (index < originalString.length())
{
numReps = 0;
char c = originalString.charAt(index);
if (!Character.isDigit(c))
{
nextChar = c;
index++;
}
else
{
while (Character.isDigit(c))
{
int temp = Integer.parseInt(""+c);
numReps = temp;
index++;
if (index >= originalString.length()) break;
c = originalString.charAt(index);
}
for (int i =0; i<numReps; i++)
{
System.out.println(nextChar);
}
}
}
}
public static void decompress(String compressedString)
{
int index = 0;
int numReps = 0;
char nextChar = ' ';
while (index < compressedString.length())
{
numReps = 0;
char c = compressedString.charAt(index);
if (!Character.isDigit(c))
{
nextChar = c;
index++;
}
else
{
while (Character.isDigit(c))
{
int temp = Integer.parseInt(""+c);
numReps = (numReps*10) + temp;
index++;
if (index >= compressedString.length()) break;
c = compressedString.charAt(index);
}
for (int i =0; i<numReps; i++)
{
System.out.println(nextChar);
}
}
}
}
}