尝试将我的数据存储在数组内的文本文件中
Trying to Store data I have in a text file inside of an Array
正在尝试 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 不太确定如何将文本文件中的信息存储到数组中,我的票证对象数组有一个名称,即地址,然后是编号,而不是数组
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());
}