我试图创建以下输出:
TOTAL SALES BY REGION
Region 1: 7,845.00
Region 2: 5,636.00
Region 3: 7,879.00
Region 4: 9,174.00
从这个数组:
double[][] sales = {{1540.0, 2010.0, 2450.0, 1845.0}, // Region 1 sales
{1130.0, 1168.0, 1847.0, 1491.0}, // Region 2 sales
{1580.0, 2305.0, 2710.0, 1284.0}, // Region 3 sales
{1105.0, 4102.0, 2391.0, 1576.0}}; // Region 4 sales
这是我到目前为止所做的,但它打印出数组中的所有数字加上累积,我如何只打印每行的总和?此外,它必须在正常的嵌套for循环中完成。
public void print(double [][] salesArray)
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
for (int i = 0; i < salesArray.length; i++) {
double sum = 0.0;
for (int j = 0; j < salesArray[0].length; j++) {
sum += salesArray[i][j];
System.out.println(sum);
}
}
}
答案 0 :(得分:1)
试试这个:
public void print(double [][] salesArray)
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
for (int i = 0; i < salesArray.length; i++) {
double sum = 0.0;
for (int j = 0; j < salesArray[0].length; j++) {
sum += salesArray[i][j];
}
System.out.println(sum);
}
}
不同之处在于您正在将打印移至外循环。这样,内部循环将执行一行的总和,然后当总和完成时,外部循环将打印它。