Brooke Brooke - 8 months ago 48
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) { = name;
this.address = address;
this.num = num;
this.year = year;
public String toString() {
return "Name: " + name + "\nAddress: " + address + "\nCustomer Number: " + num + "\nLast Order: " + year;


And here is my tester class:

import java.util.Scanner;
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(;

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

customer = new Customer(name, address, num, year);
//fill linkedList


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 Source

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.


    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 =;
        String addr2 =;
        String num2 =;
        int year2 = lineScanner.nextInt();

        Customer cust2 = new Customer(name2, addr2, num2, year2);