我需要这段代码来压缩和解压缩用户给出的字符串,压缩用户将输入“java compression -c”或“java compression”。要解压缩,它将是“java compression -d”。任何帮助,将不胜感激。它现在将编译并运行;但是,当您输入字符串时,它只会打印出压缩而不是压缩字符串。
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);
}
}
}
}
}
答案 0 :(得分:1)
您忘记了方法定义的类型参数:
public static void decompress(compressedString)
应该是
public static void decompress(String compressedString)
甚至更好
public static void decompress(final String compressedString)
答案 1 :(得分:0)
您的代码中出现了两个问题(据我所知): -
public static void decompress(compressedString)
实际应该是public static void decompress(**String** compressedString)
。您必须告诉method
它将收到的argument
类型为String
。
使用compress
和decompress
方法while (index < input.length());
。最后检查; 。你真的想要吗?您永远不会执行while
循环,因为您在它开始之前就已经终止了它。