使打印行仅打印一次并打印文件的行号

时间:2015-04-19 01:35:07

标签: java hashset line-numbers

如何保持“找不到重复项”的打印行重复而不是仅在最后获取它,如何打印我读入程序的文件的行号?

import java.util.*;
import java.io.*;

public class b{
    public static void main( String args[] ) throws Exception{
        Scanner infile = new Scanner( new File( args[0] ) );
        HashSet<String> h = new HashSet<String>();

        while(infile.hasNext()){
            String word = infile.next();
            if(h.contains(word)){
                System.out.println("DUPLICATE at line" + " " +  );
            }else if(!h.contains(word)){
                System.out.println("No Duplicate Found");
            }else{
                h.add(word);
            }   
        }
    }   
}   

1 个答案:

答案 0 :(得分:2)

import java.util.*;
import java.io.*;

public class b{
    public static void main( String args[] ) throws Exception{
        Scanner infile = new Scanner( new File( args[0] ) );
        HashSet<String> h = new HashSet<String>();
        boolean noDuplicateFound;
        lineCount = 0;

        while(infile.hasNextLine()){
            lineCount++
            String word = infile.next();
            h.add(word);
            if(h.contains(word)){
                System.out.println("DUPLICATE at line: " + lineCount);
            }else if(!h.contains(word)){
                noDuplicateFound = true;
            }
        }
        if(noDuplicateFound)
            System.out.println("No Duplicate Found");
    }   
}