Pages

Sunday, 28 August 2016

Chapter 8 Exercise 4, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**8.4 (Compute the weekly hours for each employee) 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 following array stores the work hours for eight employees. Write a program that displays employees and their total hours in decreasing order of the total hours. 
               Su M T W Th F Sa
Employee 0 2 4 3 4 5 8 8
Employee 1 7 3 4 3 3 4 4
Employee 2 3 3 4 3 3 2 2
Employee 3 9 3 4 7 3 4 1
Employee 4 3 5 4 3 6 3 8
Employee 5 3 4 4 6 3 4 4
Employee 6 3 7 4 8 3 8 4
Employee 7 6 3 5 9 2 7 9



import java.util.Scanner;
 
 
 
public class ProgramingEx8_4 {
 
 public static void main(String[] args) {
  int[][] overTime = new int[8][7];
  int[][] sum = new int[8][2];
  java.util.Scanner input = new Scanner(System.in);
  for (int i = 0; i < overTime.length; i++) {
   System.out.println("Enter over time of employee " + i);
   for (int j = 0; j < overTime[0].length; j++) {
    overTime[i][j] = input.nextInt();
   }
    
  }
   
  //sum loop
  for (int i = 0; i < overTime.length; i++) {
   for (int j = 0; j < overTime[0].length; j++) {
    sum[i][1] += overTime[i][j];
   }
   sum[i][0] = i;
  }
   
  selectionSort(sum);
   
  //printing
   
     //printing out result
      
     for (int j = sum.length-1; j >= 0; j--) {
         System.out.println("Employee " + sum[j][0] + "'s overtime is " +
           sum[j][1]);
  }
   
 }
  
 public static void selectionSort(int[][] list) {
  for (int i = 0; i < list.length - 1; i++) {
   // Find the minimum in the list[i..list.length-1]
   int currentMin = list[i][1];
   int currentMinIndex = i;
 
   for (int j = i + 1; j < list.length; j++) {
    if (currentMin > list[j][1]) {
     currentMin = list[j][1];
     currentMinIndex = j;
    }
   }
 
   // Swap list[i] with list[currentMinIndex] if necessary
   if (currentMinIndex != i) {
    list[currentMinIndex][1] = list[i][1];
    list[i][1] = currentMin;
    list[currentMinIndex][0] = list[i][0];
    list[i][0] = currentMinIndex;
 
   }
  }
 }
 
}

No comments :

Post a Comment