如何以降序显示二维数组 [英] how to display in descending order a two dimensional array
本文介绍了如何以降序显示二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按降序链接和排序二维数组.我以某种方式对我的程序进行了编码,以便您可以打印数组但它没有排序.我怎样才能让它排序?
I want to link and sort in descending order a two dimensional array. I coded my program in a way so that you can print the array but it is not sorted. How can I make it sorted?
这是一个计算8个员工一周(7天)工作小时数的程序,并按降序打印出来:
This is a program to calculate the number of hours worked by 8 employees during the week (7 days), and print them out in descending order:
public class WeeklyHours {
public static void main(String[] args) {
double[][] employeeWorkHours = {
{ 2, 4, 3, 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 } };
for (int row = 0; row < employeeWorkHours.length; row++)
System.out.println("Employee " + row + " : "
+ sumRow(employeeWorkHours, row));
}
public static double sumRow(double[][] m, int rowIndex) {
double total = 0;
for (int col = 0; col < m[0].length; col++) {
total += m[rowIndex][col];
}
return total;
}
}
这是我在控制台中得到的:
This is what I got in the console:
Employee 0 : 34.0
Employee 1 : 28.0
Employee 2 : 20.0
Employee 3 : 31.0
Employee 4 : 32.0
Employee 5 : 28.0
Employee 6 : 37.0
Employee 7 : 41.0
但我应该得到这样的东西:
But I am supposed to get something like this:
Employee 7: 41
Employee 6: 37
Employee 0: 34
Employee 4: 32
Employee 3: 31
Employee 1: 28
Employee 5: 28
Employee 2: 20
推荐答案
对您的代码进行一些更改:
With a few changes to your code:
public class WeeklyHours {
public static void main(String[] args) {
double[][] employeeWorkHours = {
{ 2, 4, 3, 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 } };
int len=employeeWorkHours.length;
double[][] employeeTotal=new double [len][2];
for (int row = 0; row < len; row++) {
employeeTotal[row][0]=row;
employeeTotal[row][1]=sumRow(employeeWorkHours, row);
System.out.println("Employee " + (int)employeeTotal[row][0] +
" : " + employeeTotal[row][1]);
}
System.out.println("\nOrder by Hours:");
Arrays.sort(employeeTotal, new java.util.Comparator<double[]>() {
public int compare(double[] a, double[] b) {
return Double.compare(b[1], a[1]);
}
});
for (int row = 0; row < len; row++)
System.out.println("Employee " + (int) employeeTotal[row][0] +
" : " + employeeTotal[row][1]);
}
public static double sumRow(double[][] m, int rowIndex) {
double total = 0;
for (int col = 0; col < m[0].length; col++) {
total += m[rowIndex][col];
}
return total;
}
这篇关于如何以降序显示二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文