ffe Lou
ffe Lou

Reputation: 11

when trying to read and create a file it cause Infinite loop

This is my piece of code where I am trying to read from a file. My file currently has 4 lines but code is not coming out of the loop after reading those lines.

public  void readPhoneBook() throws Exception {
    try {
        FileReader fileReader = new FileReader(file);
        Scanner reader = new Scanner(file);
        BufferedReader input = new BufferedReader(fileReader);

        while (reader.hasNext()) {
            String[] parts = reader.nextLine().split(" ");
            if (parts.length == 4){
                PhoneBook newPhone = new PhoneBook(parts[0],parts[1],parts[2],parts[3]);
                entryList.add(newPhone);
            }

            fileReader.close();
            reader.close();
            for (int i=0; i < entryList.size(); ++i) {
                entryList.add(new PhoneBook(entryList.get(i).getFirstName(), entryList.get(i).getLastName(),
                        entryList.get(i).getNumber(),entryList.get(i).getNote()));
                System.out.println("2"+entryList.size());
            }
        }

    } catch (Exception NoSuchElementException) {
    }
}

Upvotes: 0

Views: 55

Answers (2)

M. le Rutte
M. le Rutte

Reputation: 3563

It is not entirely clear for me what the use is of the second loop is. Using Java 8 and streaming you could implement it as follows:

public List<PhoneBook> readPhoneBook(Path file) throws Exception {
     return Files.lines(file)
         .map(line -> reader.split(" "))
         .filter(parts -> parts.length == 4)
         .map(parts -> new PhoneBook(parts[0],parts[1],parts[2],parts[3])
         .collect(Collectors.toList());
    }
}

(the other answer explained the reason why it never stops)

Upvotes: 1

ernest_k
ernest_k

Reputation: 45339

The problem is that you are continually augmenting the list, of which the size controls the loop continuation itself:

for (int i=0; i < entryList.size(); ++i) {
    ...  
    entryList.add(new PhoneBook(entryList.get(i).getFirstName(), 
        entryList.get(i).getLastName(),
        entryList.get(i).getNumber(), entryList.get(i).getNote()));

The statement entryList.add... is adding a value to the list, such that when the loop's condition is evaluated for the next iteration, entryList.size() will be bigger still.

You can fix it either by reading the size before the loop:

int entryListSize = entryList.size();
for (int i=0; i < entryListSize; ++i) {

Or, even better, by NOT adding values to the same list in the loop. In my opinion, this is the more sensible solution as it doesn't make much sense to add entries to the same list. Maybe you intended to add values to a different list object?

Upvotes: 2

Related Questions