0

我只使用循环在 java 中创建了一个矩阵。但我想在最后显示行的总数。我一直在试图解决这个问题,但我无法提出解决方案。任何帮助,将不胜感激。

这是我到目前为止的代码

public class Main {
    public static void main(String[] args) {

        int num = 4;
        int product = 0;

        for (int i = 1; i <= num; i++) {

            for (int j = 1; j <= num; j++) {

                 product = j * i;

                System.out.printf("\t" + product);


            }

            System.out.println();
        }
    }
}
4

2 回答 2

2

如果我理解正确,您只需要实现以下内容:int total = 0;然后在循环的每个循环中相应地更新......total = total + x;

于 2012-10-25T15:02:15.383 回答
1

基本上你应该做的是有一个字段来跟踪列的累积总和。

我将根据您的代码给出一个示例:

public class Main {
    public static void main(String[] args) {

    int num = 4;
    int product = 0;
    int rowSum = 0;

    for (int i = 1; i <= num; i++) {
        rowSum = 0; //reset for each row.
        for (int j = 1; j <= num; j++) {

            product = j * i;
            rowSum += product; //rowSum = rowSum + product.

            System.out.printf("\t" + product);


        }
        System.out.printf("\t = " + rowSum); //this should give you = SUM at the end of the line.
        System.out.println();
    }

}

}

于 2012-10-25T15:04:41.477 回答