Beginner
Beginner

Reputation: 143

Lottery Program (ArrayList)

I'm currently working on a program that mimics a lottery and reads the following information from a File the file includes:

5
Durant Kevin
1 15 19 26 33 46
Schofield Michael
17 19 33 34 46 47
Black Joe
1 4 9 16 25 36
Elroy Jetson
17 19 34 46 47 48
Simone Raven
5 10 17 19 34 47

I Scan in the contents of the File and created a Ticket object to hold the name and ticket number of one person however my problem occurs when I'm trying to put that information into an ArrayList any help would be appreciated.

Here is my code:

        try
    {
        Scanner scan = new Scanner(new FileInputStream(file));
        ArrayList<Ticket> info = new ArrayList<Ticket>();
        int lim = scan.nextInt();

        for(int i = 0; i < lim; i++)
        {
            String name = scan.nextLine();
            String num = scan.nextLine();
            String[] tarr = num.split(" ");
            int[] arr = new int[tarr.length];

            for(int j = 0; j < tarr.length; j++)
            {
                arr[j] = Integer.parseInt(tarr[j]);
            }

            info.add(new Ticket(name, arr[]);
        }
        scan.close();
    }

    catch(FileNotFoundException fnfe)
    {
        System.out.println("Error! The file was not found!");
    }

}

public class Ticket
{
    public String name;
    public int[] tarray;

    public Ticket(String name, int[] tarray)
    {
        this.name = name;
        this.tarray = tarray;
    }
}

Upvotes: 1

Views: 330

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521168

Your original code actually looks very clean and I only found the following problem:

info.add(new Ticket(name, arr[]);

This is not valid Java syntax for passing a variable AFAIK. If you want to pass the arr of numbers to the constructor of the Ticket class you should be doing this instead:

info.add(new Ticket(name, arr));

Update:

I have tested your code locally using IntelliJ, and the only other potential problem I found was in the following line:

int lim = scan.nextInt();

Calling Scanner.nextInt() does not update the cursor to the next line. This means that when you attempt to read the second line you will still be on the first one. A quick fix for this is to change to the following code:

int lim = scan.nextInt();   // read in number of people
scan.nextLine();            // advance to second line of input file

Upvotes: 3

A.Sharma
A.Sharma

Reputation: 2799

I believe the issue is in the constructor of the Ticket class.

You cannot just set one array equal to another. You can, however, clone it:

this.tarray = tarray.clone();

Upvotes: 0

Related Questions