import java.util.*;
public class ReadFile
{
public static class Em implements Comparable<Em>
{
private int id;
private String name;
private double Salary;
public int getId()
{
return id;
}
same get methods for sal and name
public Em(int id,String name,double e)
{
this.id=id;
this.name=name;
this.sal=sal;
}
}
public static void main (String a[]) throws IOException
{
String record;
List<Em> eL=new ArrayList<Em>();
BufferedReader br=new BufferedReader(new File("Location"));
List<String> arrList = new ArrayList<>();
try
{
while((record=br.readLine())!=null)
{
String[] rows=record.spilt(",");
Em e=null;
int a = Integer.parseInt(rows[0]);
String b=rows[1];
double c=Double.parseDouble(rows[2]);
eL.add(new Em(a,b,c);
arlist.add(Arrays.toString(rows));
System.out.println(eL.toString);
}
}//end of try
catch(IOException e)
{
e.printStackTrace();
}
}
}
請注意:檔案的位置是正確的任何錯字可能存在
該檔案包含如下資料:- 1,Duke,13000 2,Jake,14000 ...
輸出 [test.ReadFile$Em@7852e922] [test.ReadFile$Em@7852e922,test.ReadFile$Em@4e25154f]
需要幫忙 -
- 我做得對嗎
- 任何替代程式都會有所幫助
未來 - 我必須將最高薪水的員工詳細資訊寫入另一個檔案
uj5u.com熱心網友回復:
這是解決這個問題的好方法
uj5u.com熱心網友回復:
您的方法很好(如果我們忘記了您的代碼中不存在的拼寫錯誤)。您的程式輸出的原因[test.ReadFile$Em@7852e922] [test.ReadFile$Em@7852e922,test.ReadFile$Em@4e25154f]是您嘗試列印它的方式。您看到的是 ArrayList 的記憶體地址,而不是內容。要列印 ArrayList 的內容,您需要使用for 回圈按索引遍歷 ArrayList 的全部內容,然后列印其內容。這是一個簡單的例子:
for(int i = 0; i<eL.length(); i ) {
System.out.println(eL.get(i).getA)
System.out.println(eL.get(i).getB)
System.out.println(eL.get(i).getC)
}
這樣做的方法是獲取ArrayListEm中每個索引的物件El,然后使用get可以輕松添加到Em類的命令列印其 A、B 和 C 值。
uj5u.com熱心網友回復:
嘗試覆寫 Em 類中的 toString() 方法。
@Override
public String toString(){
return this.id " " this.name " " this.salary;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/444336.html
