将压缩和解压缩字符串的Java代码。 [英] Java Code that will compress and decompress a string.
本文介绍了将压缩和解压缩字符串的Java代码。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要这段代码来压缩和解压缩用户给出的字符串,压缩用户将输入java practice -c或java practice。要解压缩,它将是java practice -d。任何帮助,将不胜感激。它现在将编译并运行;但是,当你输入字符串时,它只打印出压缩而不是压缩字符串。
I need this code to compress and decompress a string given by the user, to compress the user will type either "java practice -c" or just "java practice". To decompress, it will be "java practice -d". Any help would be appreciated. It will now compile and run; however, when you type in the string it will only print out compress and not the compressed string.
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);
}
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+i);
}
}
}
}
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);
}
}
}
}
}
推荐答案
删除该行:
Remove the line:
String s = scan.next();
就在调用 compress
之前。
这篇关于将压缩和解压缩字符串的Java代码。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文