So, I have a file in which there are all presidents - their name, average initial (if any) and last name.
The file must be read, and the user can enter the name of the president to search for, and this president must be displayed.
I have a president mapping if the user searches by name or by name, but not both.
For example, an external file contains:
George,Washington,(1789-1797) Franklin,D.,Roosevelt,(1933-1945) ... and so on with all the presidents
I need the user to either enter the first name, last name, or first and last name, and get the desired result (the date does not matter for the most part).
I tried a lot of different things, but didnβt get to the presidentβs show if the user searches by name and surname.
Here is what I got so far:
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 for user input Scanner keyboard = new Scanner(System.in); // create array list of each line in presidents file ArrayList<String> presidentsArrayList = new ArrayList<String>(); // prompt user to enter a string to see if it matches with a president name System.out.println("Enter a search string of letters to find a president match: "); // store user input String userInput = keyboard.nextLine(); // add president file info to array list linesInPresidentFile while (presidentsFile.hasNextLine()) { presidentsArrayList.add(presidentsFile.nextLine()); } // end while loop String presidentNamesArray[] = presidentsArrayList.toArray(new String[presidentsArrayList.size()]); String results = searchArray(presidentNamesArray, userInput); //System.out.println("\nThe presidents who have \"" + userInput + "\" as part of their name are: "); } catch (FileNotFoundException ex) { // print out error (if any) to screen System.out.println(ex.toString()); } // end catch block } // end main // method to search for a specific value in an array public static String searchArray(String array[], String value) { for (int i = 0; i < array.length; i++) { if (array[i].toLowerCase().contains(value.toLowerCase())) { String splitter[] = array[i].split(" ,"); System.out.println(Arrays.toString(splitter)); } } return Arrays.toString(array); } }
source share