我正在尝试创建一种方法,该方法获取字符串的值以创建两个银行帐户的交易。我读取了一个.txt文件,并将每一行保存在ArrayList<String>
的条目中。
每行都有其自己的任务。最好用示例.txt文件进行解释:
2
Alice 50
Bob 70
1
Alice Bob 20 This is my reason for the transaction.
Line 1: first line marks the amount of accounts that are involved in the transactions followed.
Line 2-3: The following two lines are two accounts with the given balance.
Line 4: indicates the amount of transactions followed.
Line 5: meant to be like: Bob transfers amount 20 to Alices account with an optional
note ("This is my reason for the transaction.")
这就是我解决问题的方式:我创建了一个具有
Account
和String holder
的类int balance
。我设法使用String.split(" ")
方法将2-3行分开。但是我无法处理的下一个问题是随后的事务。我使用以下构造函数之一创建了一个名为class
的Transaction
。String receiver;
String sender;
int amount;
int timestamp;
String note;
public Transaction (String receiver, String sender, int amount, String note) {
this.receiver = receiver;
this.sender = sender;
this.amount = amount;
this.note = note;
}
我遇到的问题是我想执行事务,但是不知道如何处理第5行的
note
部分。我什至不知道如何遍历ArrayList<String> linesOfFile
并将这些部分标记在哪里它创建一个帐户(如果不存在),然后使用上面的Integer指示的每一行的交易来完成该部分。虽然我设法创建了帐户,但是不知道如何进行。我的想法是创建一个与行1相同大小的Integer。此后,我遍历文件并创建(如果不存在)具有给定余额的帐户。在标记帐户的每一行之后,我将Integer减至0,然后结束循环。但是在那之后我完全迷失了。也许我可以创建第二个循环,该循环从指示交易金额的数字开始(第4行),并遍历交易直到List结束?
答案:怎么可能将事务的最后部分设置为一个String元素?
答:刚刚在.split()方法中使用了一个限制。
Sample code would be:
ArrayList<Account> accounts;
ArrayList<String> linesOfFile = readFile("file.txt");
int count = 0;
for (String line : linesOfFile) {
if (Character.isDigit(line.charAt(0))
count = Integer.parseInt(line);
if (count != 0) {
String[] accountDetails = line.split(" ");
if (!accountExists(new Account (accountDetails[0], accountDetails[1]))) {
accounts.add(new Account(accountDetails[0], accountDetails[1]);
}
count--;
}
// This is the part I want to add for the Transactions.
}
提前致谢!
最佳答案
您不会喜欢这个答案,但是我可以问这个用例吗?
这是您在程序中的其他地方创建的文件吗(即,这是您用于练习的业余程序,并且该文件可以替代地在数据库中完成吗?)还是来自实际业务案例中,您需要导入文件到您的系统?
我问的原因是,如果可能,您可以在创建文件时在文件中添加标签,以标识要读取的字段。当然,您也可以使用数据库。