gpt4 book ai didi

java - 尝试将我的数据存储在数组内的文本文件中

转载 作者:行者123 更新时间:2023-12-01 17:13:07 25 4
gpt4 key购买 nike

尝试Java不太确定如何将文本文件中的信息存储到数组中,我的票证对象数组有一个名称,地址,然后是数字,而不是票证号码,这是数组

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());
}
}

我知道我所做的可能是完全错误的。这也是我的 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

最佳答案

您可以使用forEachRemaining读取剩余的数字,然后使用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());
}

关于java - 尝试将我的数据存储在数组内的文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61410923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com