Here's a program that creates an Employee class with
the getInfo() and printInfo() methods, and uses these methods to print
information of three employees:
Here is the implementation of the code:
class Employee {
    String name;
    int yearOfJoining;
    double salary;
    String city;
    public void
getInfo(String name, int yearOfJoining, double salary, String city) {
        this.name =
name;
       
this.yearOfJoining = yearOfJoining;
        this.salary =
salary;
        this.city =
city;
    }
    public void
printInfo() {
       
System.out.printf("%-10s %-18d %-10.2f %s\n", name,
yearOfJoining, salary, city);
    }
}
public class Main {
    public static void
main(String[] args) {
        Employee emp1
= new Employee();
       
emp1.getInfo("Ahmed", 1998, 85000, "Karachi");
        Employee emp2
= new Employee();
       
emp2.getInfo("Ali", 2002, 95500, "Islamabad");
        Employee emp3
= new Employee();
       
emp3.getInfo("Sara", 1991, 80000, "Hyderabad");
       
System.out.println("Name     
Year of joining   Salary     City");
       
emp1.printInfo();
       
emp2.printInfo();
       
emp3.printInfo();
    }
}
In this program, we define the Employee class with four
instance variables: name, yearOfJoining, salary, and city. The class also has
two methods:
getInfo(): This method takes in four arguments name,
yearOfJoining, salary, and city and sets the instance variables to their
respective values.
printInfo(): This method prints the information of an
employee in a formatted manner.
In the main() method, we create three Employee objects and
use the getInfo() method to set their information. We then print the
information of these employees using the printInfo() method.
When we run this Java program, we get the output:
Name      Year of
joining   Salary     City
Ahmed          
1998               85000.00
Karachi
Ali            
2002               95500.00
Islamabad
Sara           
1991               80000.00
Hyderabad
This output shows that the program correctly printed the
information of the three employees in a formatted manner.
here are the additional points about the code:
The System.out.printf() method is used to print the employee
information in a formatted manner. The % characters in the format string are
replaced by the corresponding argument values in the order they appear. The -
character in %-10s left-aligns the name field, while the .2 in %.2f rounds the
salary field to two decimal places.
The main() method creates three Employee objects using the
new keyword and assigns them to the emp1, emp2, and emp3 variables. The
getInfo() method is then called on each Employee object to set its information.
Finally, the printInfo() method is called on each Employee object to print its
information.
.jpg) 
 
.jpg) 
 
.jpg) 
.jpg) 
 
No comments:
Post a Comment