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!