我正在为我的 Java 入门类(class)进行编程挑战。问题是编写一个程序,将两个最流行的名字(一个“男孩”和另一个“女孩”)的 .txt 文件存储到 ArrayList 中,并要求用户输入一个名字,程序会告诉用户它是否是最受欢迎的名字之一。为了减轻一些困惑,我没有使用 FileReader 或 BufferedReader。
.txt 文件的格式为列表格式的“1 Jacob”。这是我的错误弹出的地方。如果我在程序中输入“Jacob”,它会告诉我它不在列表中,但如果我输入“1 Jacob”,它会告诉我它在列表中。有没有办法省略列表中的所有整数和制表符空格?或者有更好的方法来应对这个编程挑战吗?
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class NameSearch {
public static void main(String args[]) throws IOException {
//Open files and add to ArrayList
Path boyNames = Paths
.get("BoyNames.txt")
.toAbsolutePath();
List<String> boys = Files.lines(boyNames)
.collect(Collectors.toList());
Path girlNames = Paths
.get("GirlNames.txt")
.toAbsolutePath();
List<String> girls = Files.lines(girlNames)
.collect(Collectors.toList());
//Ask user for input
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a Boy or Girl's name to see if it's a popular name: ");
String name = keyboard.nextLine();
keyboard.close();
//Compare user input with ArrayList and print
if (boys.contains(name) || girls.contains(name))
{
System.out.println(name + " is a popular name!");
}
else
{
System.out.println("Sorry, " + name + " is not a popular name.");
}
}
}
最佳答案
很简单:
List<String> boys = Files.lines(boyNames)
.map(name -> name.replaceAll("\\d", "")) // remove numeric values
.map(name -> name.replaceAll(" ", "")) // remove spaces
.collect(Collectors.toList());
List<String> girls = Files.lines(girlNames)
.map(name -> name.replaceAll("\\d", "")) // remove numeric values
.map(name -> name.replaceAll(" ", "")) // remove spaces
.collect(Collectors.toList());
关于java - 逻辑错误; Java 姓名搜索编程挑战赛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48997380/