Here I wrote Java code to display duplicate numbers in a text file. Here I hardcoded the path name of text file. I assumed that text file contains only numbers in every line of text file.
And I like to display only those numbers which are repeated. Code is as shown below:
import java.util.*;
import java.io.*;
public class FileRead {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String,String> lines=new HashMap<String,String>();
try{
FileInputStream fstream=new FileInputStream("C:/Users/kiran/Desktop/text.txt");
DataInputStream in=new DataInputStream(fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
ArrayList arr=new ArrayList();
String str,str1;
int i=0;
while((str=br.readLine())!=null){
i++;
str1=Integer.toString(i);
if(lines.containsValue(str)){
System.out.println(str);
}else{
lines.put(str1, str);
}
}
in.close();
}catch(Exception e){
System.out.println(e);
}
}
}
Contents of text file is as shown below:
56
75
1
46
100
97
75
46
46
Expected output is:
75
46
This is the output I’m getting:
75
46
46
I’m not able to find out the error in the program. Can anyone help me??
You needed to keep track of what you have printed, for example in a
HashSet<String>.Declare
Set<String> seen = new HashSet<String>()at the top, then add anif:An even easier solution is to remove
else: