4 回答

TA貢獻1895條經驗 獲得超7個贊
在開始時聲明一個列表來收集帳戶:
import java.util.ArrayList;
...
public Account[] inReader() { //BTW: why do you pass an Account[] here?
ArrayList accountList = new ArrayList();
...
}
將 替換為for(String records : dataRecords) {...}
String name = dataRecords[0];
String cardNumber = dataRecords[1];
int pin = Integer.parseInt(dataRecords[2]); //to convert the String back to int
double balance = Double.parseDouble(dataRecords[3]);
Account account = new Account(name, cardNumber, pin, balance);
accountList.add(account);
因為您已經逐條記錄地繼續 (while ((line = br.readLine())!=null) {...})
最后return accountList.toArray(new Account[0]);

TA貢獻1836條經驗 獲得超3個贊
如上面的注釋中所述,您可以簡單地將分隔符上的行 ,然后從那里開始。split|
像這樣:
public class Account {
// ...
public static Account parseLine(String line) {
String[] split = line.split("|");
return new Account(split[0], split[1], split[2], split[3]);
}
}
應該可以正常工作(假設你有一個構造函數,它接受你放入的四件事)。如果您的類具有比這更多的信息,則可以創建一個名稱相似的類,該類僅包含此處提供的詳細信息。有了這個,只需逐行迭代,將你的行解析為其中一個,并在調用其他需要的方法時使用它的屬性(包括已經可用的 getter),等等。AccountAccountViewObjectname

TA貢獻1995條經驗 獲得超2個贊
有許多可能的方法可以做到這一點。其中之一是創建一個將保存數據的對象。例如,由于您知道您的數據將始終具有名稱,數字,數量和引腳,因此您可以創建如下類:
public class MyData {
private String name;
private String number;
private double amount;
private String pin;
// Add getters and setters below
}
然后,在讀取文本文件時,您可以列出并添加每個數據。你可以這樣做:MyData
try {
BufferedReader reader = new BufferedReader(new FileReader("path\file.txt"));
String line = reader.readLine();
ArrayList<MyData> myDataList = new ArrayList<MyData>();
while (line != null) {
String[] dataParts = line.split("|"); // since your delimiter is "|"
MyData myData = new MyData();
myData.setName(dataParts[0]);
myData.setNumber(dataParts[1]);
myData.setAmount(Double.parseDouble(dataParts[2]));
myData.setPin(dataParts[3]);
myDataList.add(myData);
// read next line
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
然后,您可以使用如下數據:
myDataList.get(0).getName(); // if you want to get the name of line 1
myDataList.get(1).getPin(); // if you want to get the pin of line 2

TA貢獻1790條經驗 獲得超9個贊
您可以逐行讀取文件,并在分隔符“|”上拆分。
下面的示例假定文件路徑位于 args[0] 中,并且將讀取然后輸出輸入的名稱組件:
public static void main(String[] args) {
File file = new File(args[0]);
BufferedReader br = new BufferedReader(new FileReader(file));
while(String line = br.readLine()) != null) {
String[] details = line.split("|");
System.out.println(details[0]);
}
}
添加回答
舉報