Java 未应答-解压缩文件程序不工作
因此,在我的文件中,我有两个列表,一个是将用于构成整个句子的唯一单词列表,另一个是压缩句子,它已压缩到唯一单词列表中单词的位置。该文件如下所示:Java 未应答-解压缩文件程序不工作,java,Java,因此,在我的文件中,我有两个列表,一个是将用于构成整个句子的唯一单词列表,另一个是压缩句子,它已压缩到唯一单词列表中单词的位置。该文件如下所示: Is, this, a, simple, sentence, 1, 2, 3, 4, 5, 3, 4, 5, 4, yourString.split("\\s*,\\s*"); 我想让我的程序使用这些独特的单词,重新创建原来的句子:这是一个简单的句子吗。但是,我的代码没有按照我希望的方式工作,因此它没有解压缩句子。这是我的密码: public
Is, this, a, simple, sentence,
1, 2, 3, 4, 5, 3, 4, 5, 4,
yourString.split("\\s*,\\s*");
我想让我的程序使用这些独特的单词,重新创建原来的句子:这是一个简单的句子吗。但是,我的代码没有按照我希望的方式工作,因此它没有解压缩句子。这是我的密码:
public static void main(String[] args) {
String compressed = "";
String compressed1 = "";
int Index1;
String orig = "";
int num1=0;
int num2=0;
BufferedReader br;
try{
br = new BufferedReader (new FileReader("CompletedWork.txt"));
try {
String Uni = br.readLine();
System.out.println(Uni); //outputs the content of the first line in the file
String Uni1 = Uni.replaceAll(",", ""); //gets rid of the commas in the unique words
String Uni2 = Uni1.toLowerCase(); //changes the case to lowercase
String[] ArrUni = Uni2.split(" "); //turns the string into a string array
System.out.println(ArrUni[0]); // checks that the array splits into words
compressed = br.readLine(); //read next line
System.out.println(compressed); //outputs the compressed
compressed1 = compressed.replaceAll(",", ""); //removes the punctuation from the compressed sentence.
System.out.println(compressed1);
String[] ArrComp = compressed1.split(" ");
System.out.println(ArrComp[2]);
for(num1=0; num1 < ArrComp.length; num1++) { //starts the loop
for(num2=0; num2 < ArrComp.length; num2++) {
if (ArrComp[num1].equals(num2)) {
orig = orig.concat(ArrUni[num2]);
}else{
}
}}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println(e); //outputs an error message if the file is not present
e.printStackTrace();
}
System.out.println(orig);
}
如您所见,在3后面有一个空格,在这里输出Orig,但不输出任何内容。我希望有人能帮我解决这个问题。如果你需要更多的信息来解决问题,尽管问。仅供参考,我对java非常陌生。问题在于您的if语句。您正在比较一个字符串(ArrComp[num1])和一个总是返回false的数字(num2) 应该是:
if (Integer.parseInt(ArrComp[num1]) == num2) {
orig = orig.concat(ArrUni[num2 - 1] + " ");
}
在获取单词时还要注意-1以避免ArrayIndexOutOfBoundsException,以及单词之间的空格
如果你愿意:
Is this a simple sentence a simple sentence is simple
那么你的压缩句子必须是:
1, 2, 3, 4, 5, 3, 4, 5, 1, 4,
通过使用正则表达式拆分逗号上的字符串,并在一行中消除额外的空间,您还可以使其他代码更高效或至少更易于阅读,如下所示:
Is, this, a, simple, sentence,
1, 2, 3, 4, 5, 3, 4, 5, 4,
yourString.split("\\s*,\\s*");