Brooke Brooke - 16 days ago 7
Java Question

Filling a linked list of objects (Nothing happens when program is run)

I'm trying to create a linked list of customer objects but i am not entirely sure how to go about filling the list. When I run the program nothing happens and the program seems to get stuck in the while loop? I dont really know

Here is my Customer class

public class Customer {
private String name;
private String address;
private String num;
private int year;

public Customer(String name, String address, String num, int year) {
this.name = name;
this.address = address;
this.num = num;
this.year = year;
}
@Override
public String toString() {
return "Name: " + name + "\nAddress: " + address + "\nCustomer Number: " + num + "\nLast Order: " + year;

}
}


And here is my tester class:

import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
import java.util.*;

public class CustomerRunner {
public static void main(String[] args) throws FileNotFoundException {
String name;
String address;
String num;
int year;
Customer customer;

LinkedList<Customer> lst = new LinkedList<Customer>();

Scanner in = new Scanner(new File("Customers.txt"));
Scanner input = new Scanner(System.in);

while(in.hasNext()) {
for (int i = 0; i < lst.size(); i++){
name = in.next();
address = in.next();
num = in.next();
year = in.nextInt();

customer = new Customer(name, address, num, year);
System.out.println(customer.toString());
//fill linkedList
lst.add(customer);
}
}
System.out.println("1");
System.out.println(lst.size());

}
}


The println(1) and println(lst.size()) are only there to try to get some sort of output.

For reference, here is my Customers.txt

Brooke MainStreet 123456789 2016
Adam MainStreet 234567890 2015
Zack MainStreet 123412341 2014
Cam MainStreet 453648576 2010
Tanya MainStreet 121212121 2005
Jason MainStreet 556574958 2004
Andrew MainStreet 777777777 2012
John MainStreet 999999999 2015
Jeff MainStreet 555444321 2010

Answer

Your for loop never loops. The ArrayList, lst, has no items initially and so its size is 0 when the for loop runs. The outer while loop keeps repeating since the Scanner never gives up any tokens with the for loop failing. Instead don't use a for loop at all but rather just use a while loop that checks when the Scanner object has run out of tokens.

e.g.,

    while (in.hasNextLine()) {
        String line = in.nextLine();

        // I scan here the line obtained, but also could split the String
        // if desired
        Scanner lineScanner = new Scanner(line);
        String name2 = lineScanner.next();
        String addr2 = lineScanner.next();
        String num2 = lineScanner.next();
        int year2 = lineScanner.nextInt();
        lineScanner.close();

        Customer cust2 = new Customer(name2, addr2, num2, year2);
        lst.add(cust2);
    }