Employee.java:
class Employee { int id; String name; double salary; Employee(int id, String name, double salary) { this.id = id; this.name = name; this.salary = salary; } } |
Main.java: Create List with 5 Employee details by reading through Scanner.
import java.util.*; class Main { public static void main(String[] args) { List<Employee> list = new ArrayList<Employee>(); Scanner sc = new Scanner(System.in); System.out.println(“Enter 5 Employee details : “); for (int i=1 ; i<=5 ; i++) { System.out.println(“Enter Emp-” + i + ” details : “); int id = sc.nextInt(); String name = sc.next(); double salary = sc.nextDouble(); Employee e = new Employee(id, name, salary); list.add(e); } System.out.println(“Details are : “); for(Employee e : list) { System.out.println(e.id + ” , ” + e.name + ” , ” + e.salary); } } } |
Store objects to list until user quits:
Employee.java:
- Create Employee class with instance variables id, name, salary
- Define parameterized constructor to initialize the object.
Main.java: Read and Add employee details until end user quits.
import java.util.*; class Main { public static void main(String[] args) { List<Employee> list = new ArrayList<Employee>(); Scanner sc = new Scanner(System.in); while(true) { System.out.println(“Enter Emp details to add : “); int id = sc.nextInt(); String name = sc.next(); double salary = sc.nextDouble(); Employee e = new Employee(id, name, salary); list.add(e); System.out.print(“Do you want to add another record(yes/no) : “); String choice = sc.next(); if(choice.equals(“no”)) { break; } } System.out.println(“Details are : “); for(Employee e : list) { System.out.println(e.id + ” , ” + e.name + ” , ” + e.salary); } } } |