Problem:
Suppose the weekly hours for all employees are stored in a two-dimensional array. Each row records an employee’s seven-day work hours with seven columns. For example, the array shown below stores the work hours for eight employees. Write a program that displays employees and their total hours in decreasing order of the total hours.
Output:
2 3 4 4 5 8 8
7 3 4 3 3 4 4
3 3 4 3 3 2 2
9 3 4 7 3 4 1
3 5 4 3 6 3 8
3 4 4 6 3 4 4
3 7 4 8 3 8 4
6 3 5 9 2 7 9
Employee's 7 worked the most with 41 hours
Employee's 6 worked the most with 37 hours
Employee's 0 worked the most with 34 hours
Employee's 4 worked the most with 32 hours
Employee's 3 worked the most with 31 hours
Employee's 1 worked the most with 28 hours
Employee's 5 worked the most with 28 hours
Employee's 2 worked the most with 20 hours
7 3 4 3 3 4 4
3 3 4 3 3 2 2
9 3 4 7 3 4 1
3 5 4 3 6 3 8
3 4 4 6 3 4 4
3 7 4 8 3 8 4
6 3 5 9 2 7 9
Employee's 7 worked the most with 41 hours
Employee's 6 worked the most with 37 hours
Employee's 0 worked the most with 34 hours
Employee's 4 worked the most with 32 hours
Employee's 3 worked the most with 31 hours
Employee's 1 worked the most with 28 hours
Employee's 5 worked the most with 28 hours
Employee's 2 worked the most with 20 hours
Solution:
import java.util.Scanner;
public class WeeklyHour
{
public static int[][] readHours()
{
Scanner scan = new Scanner (System.in);
int[][] employees = new int[8][7];
for (int i =0;i<employees.length;i++)
{
for (int j =0;j<employees[i].length;j++)
{
employees[i][j] = scan.nextInt();
}
}
return employees;
}
public static int[][] sortEmployees(int[][] employees)
{
int[][] tempar = new int[8][2];
for (int i =0;i<employees.length;i++)
{
tempar[i][0] =i;
for (int j=0;j<employees[i].length;j++)
{
tempar[i][1] += employees[i][j];
}
}
for (int i =0;i<employees.length;i++)
{
for (int j =0;j<employees.length -1;j++)
{
if ( tempar[j][1] < tempar[j+1][1] )
{
int temp = tempar[j][1];
int temp2 = tempar[j][0];
tempar[j][1] = tempar[j+1][1];
tempar[j][0] = tempar[j+1][0];
tempar[j+1][1] = temp;
tempar[j+1][0] = temp2;
}
}
}
return tempar;
}
public static void printEmployees(int[][] tempar)
{
for (int i =0;i<tempar.length;i++)
{
System.out.println("Employee's " + tempar[i][0] +
" worked the most with " + tempar[i][1] + " hours" );
}
}
public static void main (String[] args)
{
int[][] nums = readHours();
int[][] nums1 = sortEmployees(nums);
printEmployees(nums1);
}
}
No comments :
Post a Comment