-1

编写一个名为 printDuplicates 的静态方法,该方法接受包含一系列行的输入文件的 Scanner 作为其参数。您的方法应该检查每一行以查找同一行上相同标记的连续出现,并打印每个重复的标记以及它连续出现的次数。不打印不重复的标记。此问题不考虑跨多行的重复(例如,如果一行以给定标记结束,而下一行以相同标记开始)。

例如,如果输入文件包含以下文本(重复标记的序列带有下划线以强调):

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 
4

1 回答 1

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;
}
于 2012-12-17T04:54:34.527 回答