I have a project which I need help fixing my code to read a text file into an array. My coding can open the file but gives me "NoSuchElementException" error when I get to this line, String contactInfo = inFS.nextLine().trim(); If I remake out the inner loop, it goes into an infinite loop.
Here are criteria for this project, my current coding and some sample data. Any suggestions are appreciated.
Method readContactsFromFile
- Declared as public static method with a Scanner as an input parameter
- Use FileInputStream to read the file, note you will need throws IOException in the method declaration
- Returns a String multi-dimensional array that contains MAX_SIZE (30) rows and MAX_FIELDS (3) columns
- Ask user for the name of the file where the contacts are stored. Your program should add the “.txt” to the name.
- The method will read the data from the text file “?????.txt”, each line in the file contains a first name, last name, and phone number separated by a comma.  Hint: After reading each line, use the split function. The split function will read each field separated by a comma and place it into an array String contactInfo = input.nextLine().trim(); String[] contactInfoArray = contactInfo.split(","); - public static String[][] readContactsFromFile(Scanner scanner) throws IOException { String [][] contactsArray = new String[MAX_SIZE][MAX_FIELDS]; String inputFileName; String filename; FileInputStream contactsStream = null; // File input stream Scanner inFS = null; // Scanner object // Try to open file System.out.print("Enter file name: "); inputFileName = scanner.next(); filename= inputFileName+".txt"; try { contactsStream = new FileInputStream(filename); } catch (FileNotFoundException e) { e.printStackTrace(); } inFS = new Scanner(contactsStream); while(inFS.hasNextLine()){ for(int row=0;row<MAX_SIZE;row++) { String contactInfo = inFS.nextLine().trim(); String[] contactInfoArray = contactInfo.split(","); for(int column=0;column<MAX_FIELDS;column++) { contactsArray [row][column] = contactInfoArray[column]; } } } return contactsArray;- } 
Sample data from text file(without the additional line separating the records):
Emily,Watson,913-555-0001
Madison,Jacobs,913-555-0002
Joshua,Cooper,913-555-0003
Brandon,Alexander,913-555-0004
Emma,Miller,913-555-0005
 
     
    