Get print to print only once and print the file line number

How do I store the "No Duplicates" line to repeat instead of just getting it at the end, and how do I print the line number of the file I read in my program?

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

      

+3


source to share


1 answer


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

      



+2


source







All Articles