我完全迷失在数组中,需要帮助。。。这是这个项目的最终目标。。。。
在一个名为AccountArray.java的文件中,编写一个从名为customer.txt的文件中读取的客户端程序(您的主要方法)Account对象的数组,具有该数量的元素。使用"for"循环为从文件中读取的每一行信息创建一个Account对象,并将其存储到数组的元素中
这就是我目前的处境。。。我主要关心的是FileNotFound异常错误。。。。我在程序文件夹中保存了一个名为customers.txt的文件,但我需要以某种方式初始化它吗?
任何关于我在这个项目中做错的事情的其他意见都会被极大地接受,我才刚刚开始学习这些东西。
public class AccountArray {
/**
* @param args
*/
public static void main(String[] args) {
List<Account> accountsArray = new ArrayList <Account>();
String name, accountnumber, balance;
Scanner diskScanner = new Scanner(new File("customers.txt"));
Scanner scanner= new Scanner ("customers.txt");
scanner.useDelimiter(" ");
int objects= scanner.nextInt();
Account[] accounts=new Account[objects];
while (objects>0){
name = scanner.nextLine();
accountnumber = scanner.nextLine();
balance = scanner.nextLine();
for(int i = 1; i < objects; i++) {
accountsArray.add(new Account(i, name, accountnumber, balance));
}
objects=objects-1;
System.out.println(name+ " " + accountnumber + " " + balance +"n"); }// just for debugging
}
}
文件示例:
4
John Anderson
4565413
250.00
Louise Carter
2323472
1250.45
Paul Johnson
7267881
942.81
Sarah Wilson
0982377
311.26
首先,您使用了错误的Scanner
对象:
Scanner diskScanner = new Scanner(new File("customers.txt")); // Scans through your file --Use this one
Scanner scanner= new Scanner ("customers.txt"); // Scans through the String "customers.txt" --Not helpful
要修复FileNotFound异常,您需要将文件customers.txt移动到Freaky Thommi建议的new File("customers.txt").getAbsoultePath();
输出的文件夹中。
你还会遇到其他一些错误,但我会让你自己解决。。。
这是eclipse的运行形式。如果是,您需要将此文件放在项目根文件夹下。你总是可以通过使用找到绝对路径
new File("customers.txt").getAbsoultePath();
将其打印到控制台,查看文件是否存在于此位置