在 Java 中扫描文本文件时忽略其中的数字

Ignore numbers in a text file when scanning it in Java

我正在 Java 中做作业,要求我们读取两个不同的文件。一个包含前 1000 个男孩名字,另一个包含前 1000 个女孩名字。我们必须编写一个程序,returns 两个文件中的所有名称。我们必须将每个男孩和女孩的名字作为字符串读取,忽略命名的数量,并将其添加到 HashSet。添加到 HashSet 时,如果要添加的名称已经存在于 HashSet 中,add 方法将为 return false。因此,要找到常用名称,您只需在添加时跟踪哪些名称 returned false。我的问题是我不知道如何忽略每个文件中的命名数量。我的 HashSet 包含两者,我只想要名称。

这是我目前的情况。

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());
    }
}

如有任何帮助,我们将不胜感激。

尝试使用 StreamTokenizer (java.io) class 读取文件。它会将您的文件拆分为标记,并提供标记类型,如字符串值、双数据类型的数字值、文件结尾、行结尾)。这样您就可以轻松识别 String 标记。 您可以从这里找到详细信息 http://docs.oracle.com/javase/6/docs/api/java/io/StreamTokenizer.html

您也可以使用正则表达式来替换所有数字(或需要时使用更多特殊字符)

testStr = testStr.replaceAll("\d","");