kstoneman84
kstoneman84

Reputation: 7

Trying To Read A Text File Into An Array

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

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

Upvotes: 0

Views: 261

Answers (2)

Ananay Gupta
Ananay Gupta

Reputation: 385

I noticed your code could be cleaned up with some help, as there is a lot of extra stuff, which may be causing confusion.

Scanner sc = new Scanner("Test.txt");
    String line;
    while(!(line = sc.nextLine()).equals("")){
        String[] elems = line.split(",");

        //implement the rest of the code
}

This will be able to do whatever you are trying to do with the code.

As pointed out, you read the line twice. Here, the

while(!(line = sc.nextLine()).equals(""))

takes care of that, by calling first storing the nextLine in the variable line, and then checking for null equality with null.

Upvotes: 0

Curiosa Globunznik
Curiosa Globunznik

Reputation: 3205

Looks like your file has less lines than MAX_SIZE. If you remove for(int row=0;row<MAX_SIZE;row++), create a variable row and increment it in each iteration that would be one thing. You'd need to limit the loop further too while(inFS.hasNextLine() && row < MAX_SIZE) about.

Upvotes: 1

Related Questions