尝试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/