Friday, 3 November 2023

Write a java program to accept n employee names from user. Sort them in ascending order and Display them.(Use array of object and Static keyword)-Core java slip16

 

Write a java program to accept n employee names from user. Sort them in ascending 

order and Display them.(Use array of object and Static keyword)

             

 

import java.io.*;

 

import java.util.Scanner;

 

public class EmployeeSort

 {

    static class Employee

{

        String name;

 

        Employee(String name)

{

            this.name = name;

        }

 

        static void sortEmployeesByName(Employee[] employees)

           {

            for (int i = 0; i < employees.length; i++)

             {

                for (int j = i + 1; j < employees.length; j++)

                  {

                    if (employees[i].name.compareTo(employees[j].name) > 0)

                          {

                        Employee temp = employees[i];

                        employees[i] = employees[j];

                        employees[j] = temp;

                    }

                }

            }

        }

    }

 

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of employees (n): ");

        int n = scanner.nextInt();

        scanner.nextLine(); // Consume the newline character

 

        Employee[] employees = new Employee[n];

 

        // Accept employee names from the user

        for (int i = 0; i < n; i++) {

            System.out.print("Enter the name of employee " + (i + 1) + ": ");

            String name = scanner.nextLine();

            employees[i] = new Employee(name);

        }

 

        // Sort the employee names in ascending order using a static method

        Employee.sortEmployeesByName(employees);

 

        // Display the sorted employee names

        System.out.println("Sorted Employee Names:");

        for (int i = 0; i < n; i++) {

            System.out.println(employees[i].name);

        }

 

        scanner.close();

    }

}