【发布时间】:2018-08-06 10:24:06
【问题描述】:
我正在为我的 Intro Java 课程应对编程挑战。问题是编写一个程序,将两个最受欢迎的名字(一个“男孩”和另一个“女孩”)的 .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.");
}
}
}
【问题讨论】:
-
尝试在
name object上使用sub string方法
标签: java arrays arraylist file-handling