gpt4 book ai didi

java - Java中压缩和解压缩字符串的程序

转载 作者:行者123 更新时间:2023-12-01 14:03:01 30 4
gpt4 key购买 nike

我需要此代码来压缩和解压缩用户给出的字符串,要压缩,用户将键入“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);
}
}
}
}
}

最佳答案

您忘记了方法定义的类型参数:

public static void decompress(compressedString)

应该是

public static void decompress(String compressedString)

或者更好

public static void decompress(final String compressedString)

关于java - Java中压缩和解压缩字符串的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19192061/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com