KnowledgeBoat Logo

Computer Applications

The weekly hours of all employees of ABC Consulting Ltd. are stored in a two-dimensional array. Each row records an employee's 7-day work hours with seven columns. For example, the following array stores the work hours of five employees. Write a program that displays employees and their total hours in decreasing order of the total hours.

S. No.MonTueWedThuFriSatSun
Employee 085111100
Employee 111602224
Employee 245410431
Employee 347312620
Employee 43832440

Java

Java Arrays

9 Likes

Answer

import java.util.Scanner;

public class KboatABCConsulting
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        System.out.print("Enter total number of employees: ");
        int numEmps = in.nextInt();
        
        int workHours[][] = new int[numEmps][7];
        int empArr[] = new int[numEmps];
        int hours[] = new int[numEmps];
        
        //Enter employee hours in 2D array
        for (int i = 0; i < numEmps; i++) {
            System.out.println("Enter hours for Employee " + i);
            for (int j = 0; j < 7; j++) {
                workHours[i][j] = in.nextInt();
            }
        }
        
        //Calculate total hours for each employee
        for (int i = 0; i < numEmps; i++) {
            int totalHours = 0;
            for (int j = 0; j < 7; j++) {
                totalHours += workHours[i][j];
            }
            empArr[i] = i;
            hours[i] = totalHours;
        }
        
        //Sort total hours hours in decreasing order
        for (int i = 0; i < numEmps - 1; i++) {
            int index = i;
            for (int j = i + 1; j < numEmps; j++) {
                if (hours[j] > hours[index])
                    index = j;
            }
            int t = hours[i];
            hours[i] = hours[index];
            hours[index] = t;
            
            t = empArr[i];
            empArr[i] = empArr[index];
            empArr[index] = t;
        }
        
        //Display sorted total hours
        for (int i = 0; i < numEmps; i++)
            System.out.println("Employee " + empArr[i] 
                + "\t" + hours[i]);
    }
}

Output

BlueJ output of The weekly hours of all employees of ABC Consulting Ltd. are stored in a two-dimensional array. Each row records an employee's 7-day work hours with seven columns. For example, the following array stores the work hours of five employees. Write a program that displays employees and their total hours in decreasing order of the total hours.

Answered By

2 Likes


Related Questions