Here I’m reading text file which contains a integer in each line and I’m printing all the integers which appeared more than once.
As you can see I used Hash Map and I assigned integers as Key and number of occurrence of number as value.
Here I’m getting Number Format Exception here. Can anyone help me with this?
package fileread;
import java.io.*;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// TODO code application logic here
HashMap<Integer, Integer> lines = new HashMap<Integer, Integer>();
try {
FileInputStream fstream = new FileInputStream("C:/Users/kiran/Desktop/text.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = br.readLine()) != null) {
Integer intObj = Integer.valueOf(str);
if (lines.containsKey(intObj)) {
int x = 0;
x = lines.get(intObj);
if (x == 2) {
System.out.println(intObj);
}
lines.put(intObj, x++);
} else {
lines.put(intObj, 1);
}
}
in.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
It’s very likely that your number format exception is happening at this line:
See the documentation for Integer.valueOf here
I’d guess this is because one of the lines is not an integer