問題描述
我應(yīng)該讀入一個(gè)包含許多不同電子郵件地址的文件并使用數(shù)組將它們打印出來.問題是我需要消除重復(fù)的電子郵件.
I am supposed to read in a file containing many different email addresses and print them out using an array. The problem is I need to eliminate duplicate emails.
我能夠讓我的 try/catch 工作并打印出電子郵件地址.但是,我不確定如何刪除重復(fù)項(xiàng).我還不了解哈希碼或如何使用 Set
.任何幫助將不勝感激.
I was able to get my try / catch working and print out the email addresses. However, I am not sure how to go about removing the duplicates. I do not have an understanding of hashcode's or how to use a Set
yet. Any assistance would be appreciated.
這是我目前所擁有的:
import java.util.Scanner;
import java.io.*;
public class Duplicate {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter file name: ");
String fileName = keyboard.nextLine();
if (fileName.equals("")) {
System.out.println("Error: User did not specify a file name.");
} else {
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: " + fileName + " does not exist.");
System.exit(0);
}
String[] address = new String[100];
int i = 0;
while (inputStream.hasNextLine()) {
String email = inputStream.nextLine();
// System.out.println(email);
address[i] = email;
System.out.println(address[i]);
i++;
}
}
}
}
推薦答案
簡單的解決方案是使用java的Set,
The Simple solution is that use Set of java,
所以設(shè)置自動(dòng)刪除重復(fù)值
so set remove duplicate value automatically
在您的代碼中,您有數(shù)組而不是轉(zhuǎn)換數(shù)組以直接使用代碼設(shè)置
and in your code you have array than convert array to set directly using code
Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));
這篇關(guān)于Java從數(shù)組中刪除重復(fù)項(xiàng)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!