1

So I have a text file with president names, which needs to be read in, and then a user can enter the name of a president (first name or last name), and then all presidents with said name (first or last) should be displayed to screen.

Here is the code:

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

}

Ok, so everything works as it should, except I would like that if someone types in like "john" for example. it prints out the presidents that are named John, and not the presidents that have the string "john" in their name.

If anyone has any pointers, they would be greatly appreciated!

4
  • Could do this with regex, where president's name matches the regex "\bjohn\b", which will match the word "john" Commented Nov 12, 2015 at 16:32
  • Not familiar with regex, so wouldn't even know where to start as far as that goes. Thanks tho... Commented Nov 12, 2015 at 16:41
  • Just use String.contains() to make the search it should find the string if its starting ending or in the middle Commented Nov 12, 2015 at 16:51
  • Exactly, but I don't want it to just find the string, I need it to find the specific name... Commented Nov 12, 2015 at 16:57

2 Answers 2

1

Assuming the name appears before the surname, just modify your if statement like this

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

Also I would recommend to rewrite the for loop like this

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

So simply iterate over linesInPresidentsFile no need to make an array. And most importantly check that the split returned an array with 3 String before accessing.

Sign up to request clarification or add additional context in comments.

5 Comments

Oh, thanks alot! What if I want to type in a presidents last name as an option too? Any ideas?
If you know the last name will be ... last, then there is also a method endsWith
Yea I figured that, but the end of the actual string is a date range which the president was in office, so that wouldn't work. Thanks for the advice tho, it was a big help!!
You seem to split each line anyway in name, last name and date range so equals is your friend
Hey again. So everything is working if I search by first name, or by last name. But if I type the president's full name, nothing comes up. I been trying a whole host of different things, but because of that comma that separates that first and last name in the array, it does not detect it. Any workarounds you might have? Thank you!
0

Why not wrap up each entry in a President class:

public class President {

    private String firstName;
    private String lastName;

    // Constructor + Getters & Setters
}

Then when you read your Presidents.txt file create a List<President> of all the entries.

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

With a method to create the list from the entries in the file, something like:

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

Then when you want to filter those with the first name "John" you can search for those with the first name equal to "John".

If you are using Java 8 you can do something like the following;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.