-1
我有一個關於文件讀寫的問題,因爲我最近才知道他們。在讀指南文件
如果我有文件包含類似的數據:
1 apartment 600000 2 house 500000 3 house 1000 4 something 5456564
(ID名稱價格/ INT字符串雙)
這一切在1號線,
我可以這樣做instanceof
所以我可以像房屋的所有價格一樣計算1型 的價格嗎?
我有一個關於文件讀寫的問題,因爲我最近才知道他們。在讀指南文件
如果我有文件包含類似的數據:
1 apartment 600000 2 house 500000 3 house 1000 4 something 5456564
(ID名稱價格/ INT字符串雙)
這一切在1號線,
我可以這樣做instanceof
所以我可以像房屋的所有價格一樣計算1型 的價格嗎?
這我不清楚你目前如何存儲你在讀取數據,但你應該做的是將數據讀入一些數據對象的列表:
public class Dwelling
{
int Id;
String name;
int price;
}
然後將這些存儲一些數據結構體。我想的ArrayList的一個HashMap可能會爲你的目的是方便:
HashMap<String, ArrayList<Dwelling>> types = new HashMap<String, ArrayList<Dwelling>>();
// Loop through records in file
while(moreRecords)
{
// Read the next record into a data object
DwellingType d = getNextDwelling();
// Store the record in the data structure
ArrayList<Dwelling> list = types.get(d.getName());
if (list == null)
{
list = new ArrayList<Dwelling>();
types.put(d.getName(), list);
}
list.add(d);
}
要訪問的特定類型的記錄列表,您只需要調用HashMap.get()
:
ArrayList<Dwelling> list = types.get("Apartment");
,那麼你可以只是循環通過記錄做你需要做的任何事情:
int totalPrice = 0;
for (Dwelling d : list)
{
totalPrice += d.price;
}
感謝編輯,杜克! –
這是Java嗎? (基於'instanceof')。這個問題很難理解。這可能會回答你的問題 - 'instanceof'是用於檢查對象是否是某種類型的,你不能用它來相互比較字符串(字符串都具有相同的類型 - 'String'(在Java中))。但是你可以使用'yourString.equals(「house」)'。 – Dukeling
對不起,忘記說明語言,是的,它是Java。我熟悉FileReader,BufferedReader和使用Scanner在while循環中讀取文件以讀取行。不知道yourString.equals(「家」) – Abdelrahman
有很多導遊,無論在文件讀取和的instanceof。沒有必要問這個問題。它不會幫助你。 – Val