Lushmoney
Lushmoney

Reputation: 480

Print out certain characters from array based on user input

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!

Upvotes: 1

Views: 368

Answers (2)

kstandell
kstandell

Reputation: 785

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

Upvotes: 0

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22234

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.

Upvotes: 1

Related Questions