Write a program to read ID, Name, address, salary of twenty employees from keyboard and write in into the file “emp.doc”. Again read records of the employees and display records of those students whose salary is more than 25000.
//Employee.java
import java.io.RandomAccessFile;
import java.util.Scanner;
public class Employee {
private int id;
private String name;
private String address;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public static void main(String []args) {
final int size = 20;
int i;
Employee e[] = new Employee[size];
Scanner sc = new Scanner(System.in);
int id;
String n;
String a;
double s;
//setting student objects
for(i=0; i<size; i++) {
e[i] = new Employee();
System.out.println("Enter id of emp "+(i+1)+":");
id = sc.nextInt();
System.out.println("Enter name:");
n = sc.next();
System.out.println("Enter address:");
a=sc.next();
System.out.println("Enter salary:");
s=sc.nextDouble();
e[i].setId(id);
e[i].setName(n);
e[i].setAddress(a);
e[i].setSalary(s);
}
//write to file
try {
RandomAccessFile f = new RandomAccessFile("D:\\emp.doc","rw");
for(i=0;i<size;i++) {
f.write(e[i].getId());
f.writeUTF(e[i].getName());
f.writeUTF(e[i].getAddress());
f.writeDouble(e[i].getSalary());
}
f.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
//read from file and display salary greater than 25000
int id1[] = new int[size];
String naam[] = new String[size];
String add[] = new String[size];
double sal[] = new double[size];
try {
RandomAccessFile f = new RandomAccessFile("D:\\emp.doc","r");
for(i=0;i<size;i++) {
id1[i] = f.read();
naam[i] = f.readUTF();
add[i] = f.readUTF();
sal[i] = f.readDouble();
if(sal[i]>25000) {
System.out.println("ID:"+id1[i]+"\tName:"+naam[i]+"\tAddress:"+add[i]+"\tSalary"+sal[i]);
}
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
Comments
Post a Comment