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();
}
}
}
Please Note: Loation of file is correct Any typo might be there
The file contains data as follows:- 1,Duke,13000 2,Jake,14000 ...
OUTPUT [test.ReadFile$Em@7852e922] [test.ReadFile$Em@7852e922,test.ReadFile$Em@4e25154f]
Need help -
- Am I doing it correctly
- Any alternate program will help
Future - I have to write emp details who has maximum salary into another file
CodePudding user response:
It is a good approach to tackle this problem
CodePudding user response:
Your approach is good (if we forget the typos which, I assume, are not present in your code). The reason your program is outputting [test.ReadFile$Em@7852e922] [test.ReadFile$Em@7852e922,test.ReadFile$Em@4e25154f]
is because of the way you are trying to print it. What you see is the memory adress of your ArrayList, not the content. To print the content of your ArrayList, you need to use a for loop that goes through the entire content of you ArrayList index by index and then prints its content. Here's a quick example :
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)
}
This way of doing it gets the Em
object for every index in the El
ArrayList, and then prints its A,B and C value using a get
command that you can easily add to your Em
Class.
CodePudding user response:
Try overriding toString() method in Em class.
@Override
public String toString(){
return this.id " " this.name " " this.salary;
}