【发布时间】:2018-04-16 17:33:54
【问题描述】:
我正在尝试使用 swing 制作联系人簿,但在用文件中的数据填充文本字段时遇到问题。
我有名字,姓氏,地址和电话号码(字符串)的框,文本文件的结构是这样的:
Name
Surname
Address
Phone
Name
Surname
Address
Phone
...
我有一个 ArrayList 来保存联系人,当我没有从文件中读取数据时,我使用了 contacts.add(String, String, String, String) 我成功地在 TextFields 中显示了数据。
我试过这个从文件中读取,但它似乎不起作用。
试试{
this.myFile = new File("contacts.txt");
this.scan = new Scanner(myFile);
while (scan.hasNext()) {
contact = new Contact(scan.next(), scan.next(), scan.next(), scan.next());
contacts.add(contact);
}
}
catch (InputMismatchException e) {
System.err.println("Invalid");
}
catch (FileNotFoundException e) {
System.err.println("Not found");
}
finally {
if (scan != null) {
scan.close();
}
else {
System.out.println("empty");
}
}
使用数据库会更容易/更好吗? 谢谢
【问题讨论】:
-
联系人是联系人对象的 ArrayList 吗?另外,您遇到了什么样的错误?
-
是 ArrayList
联系人 = new ArrayList (); -
你得到什么错误?
-
@EmreDalkiran 我得到一个 NoSuchElementException
-
我在下面编辑了我的评论。
标签: java swing arraylist java.util.scanner jtextfield