如何防止“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/