Define a class named Employee with the following fields: empID , empName , deptID , bloodGroup , salary. Define following methods : setEmployeeDetails( ), printEmployeeDetails( ) Prompt the user to enter values.
Objective
Define an Employee class with state (fields) and behavior (methods) to set and print details.
Algorithm / Approach
- Create an
Employeeclass with fields:empID,empName,deptID,bloodGroup, andsalary. - Define a
setEmployeeDetail()method that uses aScannerto read input from the user and assign them to the fields. - Define a
printEmployeeDetails()method that prints out all the fields in a formatted way. - In the
mainmethod, create anEmployeeobject. - Call the
setEmployeeDetail()method on the object. - Call the
printEmployeeDetails()method on the object.
Employee.java
import java.util.Scanner;
class Employee {
int empID,deptID,salary;
String empName,bloodGroup;
void setEmployeeDetail() {
Scanner s=new Scanner(System.in);
System.out.print("Enter empId: ");
empID=Integer.parseInt(s.nextLine());
System.out.print("Enter Name: ");
empName = s.nextLine();
System.out.print("Enter Dept. Id: ");
deptID=Integer.parseInt(s.nextLine());
System.out.print("Enter Blood Group: ");
bloodGroup= s.nextLine();
System.out.print("Enter Salary: ");
salary=Integer.parseInt(s.nextLine());
}
void printEmployeeDetails() {
System.out.println("EMP. ID - "+empID+
"\nEMP NAME - "+empName+
"\nDEPT ID - "+deptID+
"\nBLOOD GROUP - "+bloodGroup+
"\nSALARY - "+salary);
}
public static void main(String[] a)
{
Employee e = new Employee();
e.setEmployeeDetail();
e.printEmployeeDetails();
}
}
Expected Output
Enter empId: 12 Enter Name: Alok Enter Dept. Id: 5 Enter Blood Group: A Enter Salary: 30000 EMP. ID - 12 EMP NAME - Alok DEPT ID - 5 BLOOD GROUP - A SALARY - 30000
Explanation of the Program
- This program demonstrates how objects encapsulate data (fields) and operations (methods) together.
- The fields define the properties every Employee will have. The methods define what an Employee can do.
- Because the fields are declared at the class level (instance variables), they are accessible by both the
setEmployeeDetailandprintEmployeeDetailsmethods. - Notice the use of
Integer.parseInt(s.nextLine()). This prevents the common scanner bug where reading an integer leaves a newline character in the buffer, which would accidentally skip the next String input.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Using
nextInt()followed directly bynextLine()without clearing the buffer, causing the String input to be skipped.