[英]How to merge two lists with different variable types
正如问题所述,我想知道将两个具有不同变量类型的列表合并在一起的最佳方法是什么。 我不确定我解决这个问题的方法是否正确,所以我很乐意接受有关此问题的所有建议。 基本上我正在制作银行应用程序。 当用户完成时,一些交易数据被添加到表单(类型日期金额)的 txt 文件中。 我希望用户稍后能够进行更多交易,并将这些新交易添加到此 txt 文件的末尾。
我的问题是,当我重新阅读用户以前的交易时,我将它们作为字符串列表读入
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(account.getName()+"Transactions.txt"));
String line;
while ((line = br.readLine()) != null) {
transactions.add(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
br.close();
}
但是,要添加到我的 txt 文件中的事务列表的类型是事务而不是字符串。
List<Transaction> transactionsToAdd = new ArrayList<Transaction>()
作为一个例子,这里有一些代码在用户存款的情况下。
case 1:
amount = scanner.DepositScanner();
balance = account.Deposit(balance, amount);
System.out.print("Your new balance is: " + balance);
String depositFullDate = dateManager.getDateAsString();
Transaction depositTransaction = new Transaction("Depsoit", amount, depositFullDate);
transactionsToAdd.add(depositTransaction);
break;
理想情况下,我希望代码读取用户以前的交易,将他们的新交易添加到 txt 文件的末尾,然后在用户完成后将所有这些保存到同一个 txt 文件中。 有没有办法以 Transaction 类型而不是 String 类型读取用户以前的交易,或者以某种方式将这两个列表组合起来给我一个大列表以保存到我的 txt 文件中。
我的交易 class 如下
public class Transaction {
String details;
String date;
Double amount;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Transaction(String details, double amount, String date) {
super();
this.details = details;
this.date = date;
this.amount = amount;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public Double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
编辑 1 - 为我的交易 class 添加了代码
将您的交易列表转换为 JSON 数组:(按照下面的链接)
然后,当您想创建一个新事务时,您可以将整个文件读取为 JSON 数组,并从中获取您的事务对象。 您将需要遍历 JSON 数组来获取您的事务对象。 (要获取 Transaction 对象,您必须使用 ObjectMapper)。
看到这个:
我实际上遇到了同样的问题,但提供给我的解决方案不涉及 JSON。 我也在使用扫描仪来读取 .txt 文件而不是 BufferedReader(idk 如何使用它)。
我假设您的 txt 文件看起来像这样。 仅包含这些单词并由单个空格分隔。 因为你还没有展示如何在 transactions.txt 中写东西的方法
Deposit 42069 11/05/2021
Deposit 360 11/05/2021
//so on
这就是您读取它并将其存储在 object 类型的 ArrayList 中的方式。
//transactionToAdd is the name of your arraylist
//Transaction is the name of your class
String line = reader.readLine();
String[] array = line.split(" ")// use same delimiter used to write
if(array.lenght() ==3){ // to check if data has all three parameter
transactionToAdd.add(new Transaction(array[0], Double.parseDouble(array[1]), array[2] ));
// you have to handle case if Double.parseDouble(array[2]) throws exception
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.