编写一个名为printDuplicates的静态方法,作为其接受 参数扫描器,用于包含一系列行的输入文件。 您的方法应检查每行寻找连续 在同一行上出现相同的标记,并打印每个 重复的标记以及它连续出现的次数。 不打印非重复的标记。重复多行 (例如,如果一行以给定标记结束并且下一行开始 在这个问题中不考虑使用相同的标记。
例如,如果输入文件包含以下文本(序列 重复标记的重点强调):
hello how how are you you you you I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge bow wow wow yippee yippee yo yippee yippee yay yay yay one fish two fish red fish blue fish It's the Muppet Show, wakka wakka wakka
您的方法将为前面的输入生成以下输出 文件:
how*2 you*4 I*3 Jack's*2 smirking*5 wow*2 yippee*2 yippee*2 yay*3 wakka*3
我现在在java中的代码是以下,但是没有成功,我想知道为什么。如果有人能提供帮助那就太棒了,谢谢你:)。
import java.io.*;
import java.util.*;
public class What {
public static void main(String[] args) throws Exception {
String word = "";
String word2 = "";
Scanner input = new Scanner(new File("what.txt"));
while(input.hasNextLine()) {
Scanner line = new Scanner(input.nextLine());
int repeat = 1;
word = line.next();
while(line.hasNext()) {
word2 = line.next();
while(word.equals(word2) && line.hasNext()) {
word = word2;
word2 = line.next();
repeat++;
}
if(repeat!=1) {
System.out.print(word + "*" + repeat + " ");
}
word = word2;
}
System.out.println();
}
}
}
what.txt包含以下内容:
hello how how are you you you you I I I am Jack's Jack's smirking smirking smirking smirking smirking revenge bow wow wow yippee yippee yo yippee yippee yay yay yay one fish two fish red fish blue fish It's the Muppet Show, wakka wakka wakka
现在的输出是:
how*2 are*2 you*4
I*3 am*3 jack's*4 smirking*7
wow*2 yippee*3 yo*3 yippee*4 yay*5
wakka*2
答案 0 :(得分:0)
试试这个:
while(line.hasNext()) {
word2 = line.next();
while(word.equals(word2)) {
repeat++;
if(line.hasNext()){
word2 = line.next();
} else {
break;
}
}
if(repeat!=1) {
System.out.print(word + "*" + repeat + " ");
}
repeat = 1;
word = word2;
}