java - 获取打印行只打印一次并打印文件的行号

标签 java hashset line-numbers

如何防止“No Duplicates Found”打印行重复而不是只在末尾获取它,以及如何打印我读入程序的文件的行号?

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);
            }   
        }
    }   
}   

最佳答案

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");
    }   
}   

关于java - 获取打印行只打印一次并打印文件的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29724852/

相关文章:

java - 在 Java 中如何附加到文本文件而不是覆盖它?

java - JSF 2 中 JSTL forEach 的问题

java - 如何将字符串添加到 LinkedHashSet?

Unix 命令获取 csv 文件中的行数

c - 如何在C中获取文件中所有函数的范围(即行号)?

Java REST WS下载docx

java.lang.ClassNotFoundException : org. apache.Struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

java - Java中Tree和Hash(Sets-Maps)的区别

java - HashSet 并在 JList 上显示

unix - 使用 sed 从文本文件中删除特定行号?