【发布时间】:2015-11-26 06:17:14
【问题描述】:
我目前正在开发一个模仿彩票的程序,并从 File 文件中读取以下信息:
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
我 Scan 在 File 的内容中创建了一个 Ticket 对象来保存一个人的姓名和票号但是当我尝试将该信息放入 ArrayList 时出现问题任何帮助将不胜感激。
这是我的代码:
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;
}
}
【问题讨论】:
-
为了将来参考,最好在问题中包含堆栈跟踪。
-
不需要
FileInputStream。new Scanner(file)会做到的。尽管您可能希望将其移至try语句,即使用 try-with-resources。
标签: java arrays file arraylist