简体   繁体   中英

Trying to Store data I have in a text file inside of an Array

Trying out Java not too sure how to store information from a text file into an array, my array of ticket objects have a name the address then number than ticket numbers which are Arrays

public static void readTicket(ArrayList<Ticket>tickets) throws IOException
    {
        String name;
        String address;
        int phone;
        int [] numbers;
        //1 create file
        File file1 = new File("ticketdata.txt");        
        //2 create a file writer class
        FileWriter fw = new FileWriter(file1);
        //3 create a print writer class
  //pass participants through

        Scanner scan = new Scanner(file1);

        while(scan.hasNextLine())
        {
            name = scan.next();
            address = scan.next();
            phone = scan.nextInt();
            numbers = scan.next(); //error
            tickets.add(new Ticket(name, address, phone, numbers));
            System.out.println(scan.nextLine());
        }
    }

I know what I've done is probably completely wrong. also this is what i have in my ticketdata.txt

Maribel Lagos 899545432 1 2 3 4
Rilwan London 899677667 2 3 5 10
Darren Dundalk 899778998 13 15 19 20
Masaki Tokyo 899765431 4 9 11 23

You can read the remaining numbers using forEachRemaining and then convert to array with toArray()

 while(scan.hasNextLine())
{
    List<Integer> numbersList = new ArrayList<>();
    name = scan.next();
    address = scan.next();
    phone = scan.nextInt();
    numbers = scan.forEachRemaining(e->numbersList.add(Integer.valueOf(e))); 
    tickets.add(new Ticket(name, address, phone, numbersList.toArray()));
    System.out.println(scan.nextLine());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM