根据用户输入从数组中打印出某些字符

时间:2015-11-12 16:26:08

标签: java arrays

所以我有一个带有总统姓名的文本文件,需要读入,然后用户可以输入总统的名字(名字或姓氏),然后输入所有姓名的总统(第一个或最后一个) )应显示在屏幕上。

以下是代码:

import java.util.*;
import java.io.*;

public class NameSearch {

public static void main(String[] args) throws IOException {
    try {
        // read from presidents file
        Scanner presidentsFile = new Scanner(new File("Presidents.txt"));
        Scanner keyboard = new Scanner(System.in);
        // create array list of each line in presidents file
        ArrayList<String> linesInPresidentsFile = new ArrayList<String>();

        String userInput = keyboard.nextLine();

        // add president file info to array list linesInPresidentFile
        while (presidentsFile.hasNextLine()) {
            linesInPresidentsFile.add(presidentsFile.nextLine());
        }

        for (int i = 0; i < linesInPresidentsFile.size(); i++) {
            // store elements in array list into array literal
            String presidentNames[] = linesInPresidentsFile.toArray(new String[i]);

            if (presidentNames[i].toLowerCase().contains(userInput.toLowerCase())) {
                String splitInfoElements[] = presidentNames[i].split(",", 3);
                System.out.println(splitInfoElements[0] + " " + splitInfoElements[1] + " " + splitInfoElements[2].replace(",", " "));
            }

        }

    } catch (FileNotFoundException ex) {
        // print out error (if any) to screen
        System.out.println(ex.toString());
    }
}

}

好的,所以一切都按照预期的方式运作,除非我愿意,如果有人输入类似&#34; john&#34;例如。它打印出名为约翰的总统,而不是那些拥有字符串&#34; john&#34;以他们的名义。

如果有人有任何指示,他们将不胜感激!

2 个答案:

答案 0 :(得分:1)

假设姓名出现在姓氏之前,只需像这样修改你的if语句

if (presidentNames[i].toLowerCase().startsWith(userInput.toLowerCase()))

另外我建议像这样重写for循环

for (String fullName : linesInPresidentsFile) {
    if (fullName.toLowerCase().startsWith(userInput.toLowerCase())) {
        String splitInfoElements[] = fullName.split(",", 3);
        if (splitInfoElements.length == 3) {
            System.out.println(splitInfoElements[0] + " " + splitInfoElements[1] + " " + splitInfoElements[2].replace(",", " "));
        }
    }
}

所以简单地遍历linesInPresidentsFile就不需要创建数组了。最重要的是,在访问之前检查拆分是否返回了一个包含3 String的数组。

答案 1 :(得分:0)

为什么不包括President类中的每个条目:

public class President {

    private String firstName;
    private String lastName;

    // Constructor + Getters & Setters
}

然后当您阅读Presidents.txt文件时,创建所有条目的List<President>

List<President> presidents = createPresidentList(
            Files.readAllLines(Paths.get("Presidents.txt"), Charset.defaultCharset()));

使用从文件中的条目创建列表的方法,如:

private List<President> createPresidentList(List<String> entries) {
    List<President> presidents = new ArrayList<>();
    for (String entry : entries) {
        String[] values = entry.split(",");
        presidents.add(new President(values[0], values[1])); 
    }
    return presidents;
}

然后,当您想要过滤名为“John”的那些时,您可以搜索名字等于“John”的那些。

如果您使用的是Java 8,则可以执行以下操作;

String firstName = ... // The name you want to filter on ("John") taken from the user

...

List<President> presidentsByFirstNameList = presidentList.stream().filter(p -> p.getFirstName().equals(firstName)).collect(Collectors.toList());