在Java中扫描时忽略文本文件中的数字
我正在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());
}
}
任何帮助,将不胜感激。
你也可以使用正则表达式(如果需要以上的特殊字符),以取代所有数字
testStr = testStr.replaceAll("\\d","");
尝试使用StreamTokenizer(java.io)类读取文件。它会将您的文件拆分为令牌,并提供类似字符串的令牌类型,双数据类型的数值,文件结尾,行尾)。所以您可以轻松识别String标记。 你可以找到从这里 http://docs.oracle.com/javase/6/docs/api/java/io/StreamTokenizer.html
这是一件很有意思的事。我会进一步调查。感谢您的帮助。 – Arem
是有一个确切的图案的详细资料?像“名字 - 号码”?如果是这样,你可以分割文件。 'String line = s.next()。split(“ - ”)[0]'。空格和逗号也一样。只显示该文件的几行 –