我會用兩套方法;
public static void main(String[] args) {
Set<Integer> result = new HashSet<Integer>();
Set<Integer> temp = new HashSet<Integer>();
try{
FileInputStream fstream=new FileInputStream("text.txt");
DataInputStream in=new DataInputStream (fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String str;
while((str=br.readLine())!=null){
if (!"".equals(str.trim())){
try {
Integer strInt = new Integer(str.trim());
if(temp.contains(strInt)){
result.add(strInt);
} else {
temp.add(strInt);
}
} catch (Exception e){
// usually NumberFormatException
System.err.println(e);
}
}
}
in.close();
}
catch(Exception e){
System.err.println(e);
}
for(Integer resultVal : result){
System.out.println(resultVal);
}
}
或者,你也可以使用一個單一的HashMap與HashMap.Key作爲整數和HashMap.Value作爲計數爲整數。 然後,如果您以後需要重構查找具有單個事件的所有實例,那麼您可以輕鬆地完成此操作。
public static void main(String[] args) {
Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();
try{
FileInputStream fstream=new FileInputStream("text.txt");
DataInputStream in=new DataInputStream (fstream);
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String str;
while((str=br.readLine())!=null){
if (!"".equals(str.trim())){
try {
Integer strInt = new Integer(str.trim());
int val = 1;
if(frequency.containsKey(strInt)){
val = frequency.get(strInt).intValue() + 1;
}
frequency.put(strInt, val);
} catch (Exception e){
// usually NumberFormatException
System.err.println(e);
}
}
}
in.close();
}
catch(Exception e){
System.err.println(e);
}
// this is your method for more than 1
for(Integer key : frequency.keySet()){
if (frequency.get(key).intValue() > 1){
System.out.println(key);
}
}
// This shows the frequency of values in the file.
for(Integer key : frequency.keySet()){
System.out.println(String.format("Value: %s, Freq: %s", key, frequency.get(key)));
}
}
小心NumberFormatExceptions,並根據您的情況,您可以處理它們的循環中,或外循環。
想要從文件中讀取所有1個文件並顯示給用戶嗎? – 2012-01-05 14:34:44
如果這是家庭作業,它應該被標記爲這樣。 – Perception 2012-01-05 14:48:33