我正在Java中執行一項任務,要求我們讀取兩個不同的文件。一個擁有前1000名男孩的名字,另一個包含前1000名女孩的名字。我們必須編寫一個程序來返回兩個文件中的所有名稱。我們必須讀取每個男孩和女孩的名字作爲一個字符串,忽略namings的數量,並將其添加到HashSet。當添加到HashSet時,如果要添加的名稱已經存在於HashSet中,add方法將返回false。所以要找到常用的名字,你只需要追蹤添加時返回的錯誤名稱。我的問題是,我無法弄清楚如何忽略每個文件中的命名數量。我的HashSet包含兩個,我只想要名稱。在Java中掃描時忽略文本文件中的數字
這是我到目前爲止。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Names {
public static void main(String[] args) {
Set<String> boynames = new HashSet<String>();
Set<String> girlnames = new HashSet<String>();
boynames = loadBoynames();
System.out.println(girlnames);
}
private static Set<String> loadBoynames() {
HashSet<String> d = new HashSet<String>();
File names = new File("boynames.txt");
Scanner s = null;
try {
s = new Scanner(names);
} catch (FileNotFoundException e) {
System.out.println("Can't find boy names file.");
System.exit(1);
}
while(s.hasNext()){
String currentName = s.next();
d.add(currentName.toUpperCase());
}
return d;
}
}
我的計劃是採取我現在已經和女孩的名字添加到它的HashSet的,但我做之前,我需要沒有數字在我的HashSet。
我嘗試使用此代碼跳過的數字,但它只是吐出了錯誤
while(s.hasNextLine()){
if (s.hasNextInt()){
number = s.nextInt();
}else{
String currentName = s.next();
d.add(currentName.toUpperCase());
}
}
任何幫助,將不勝感激。
是有一個確切的圖案的詳細資料?像「名字 - 號碼」?如果是這樣,你可以分割文件。 'String line = s.next()。split(「 - 」)[0]'。空格和逗號也一樣。只顯示該文件的幾行 –