我不知道如何创建一个方法,以便在创建数组后将列相加。行和列是随机创建的,但我试图在最后添加每个列。方法在我的代码被称为sumTotal,有什么建议吗?谢谢!
public static void printMonths(String[]months){
for (int i=0; i<months.length; i++)
System.out.printf("%-20s", months[i]);
}
public static void startSales (double[][] array){
for (int row=0; row<array.length; row++)
for (int col=0; col<array[row].length; col++)
array[row][col] = (int)(Math.random()*10000);
}
public static void printSales (double [][] array){
for (int row=0; row<array.length; row++){
for(int col=0; col<array[row].length; col++)
System.out.printf("L. %10.2f ", array[row][col]);
System.out.println();
}
}
public static void repeat (char c, int n){
for(int i=0; i<n; i++)
System.out.print(c);
}
/* public static void sumTotal(double[][]array){
for (int i=0; i<row.length; i++){
for (int j=0; j<col.length; j++)
System.out.println("");
}
}*/
public static void main(String[] args) {
Scanner inputNumber = new Scanner(System.in);
Scanner inputText = new Scanner(System.in);
String name;
int rows = 10;
double total;
String [] months = {"January", "February", "March"};
System.out.print("Type complete name: ");
name = inputText.nextLine();
System.out.print("Type number of rows: ");
rows = inputNumber.nextInt();
if (rows>0){
double[][] sales = new double [rows][3];
startSales(sales);
System.out.print("nSales Reportnn");
System.out.print("Salesman: " + name + 'n');
System.out.println();
repeat('=', 60);
System.out.println();
printMonths(months);
System.out.println();
repeat('=', 60);
System.out.println();
printSales(sales);
repeat('=',60);
System.out.println();
}
我还没有执行和编译这些代码,但是下面的代码可能会给你一个好的开始。
Version 1 (Get sum of specific column)
public static int sumTotal(double[][] array, int col)
{
int total = 0;
for (int i = 0; i < array.length; i++)
{
total += array[i][col];
}
return total;
}
int sum = sumTotal(myArray, 3); //sum of only column 4 starting from 0 index
Version 2 (Get sum of all columns)
public static int[] sumTotal(double[][] array, int totalcols)
{
int[] total = new int[totalcols];
for (int i = 0; i < total.length; i++)
{
total[i] = 0; //initialize to 0
}
for (int i = 0; i < total.length; i++)
{
for (int j = 0; j < array.length; j++)
{
total[i] += array[j][i];
}
}
return total;
}
int[] sum = sumTotal(myArray, 6) //6 is the total columns count you will get 1D array of sum of 6 columns