java - 需要帮助嵌套 for 循环来添加 java 中表中的所有行和列

标签 java for-loop methods static nested-loops

问题是:读取表格中给出的一组数字,并显示总数。 (添加行和列) 这是我到目前为止所拥有的。我需要有关如何获得正确输出的指导。提前致谢。

*不想使用数组。

import java.util.Scanner;
public class tableintegers {

    public static void main(String[] args) {

        Scanner input=new Scanner(System.in);

        System.out.print("Give the number of rows and number of columns: ");
        int rows=input.nextInt();
        int cols=input.nextInt();

        int total=0, sum=0, numbers=0;
        for(int i=0;i<rows; i++) {

            if (rows>i) { 
                System.out.print("Enter row " +(i+1)+ ":");
                numbers=input.nextInt();
                input.nextInt();
            }

            sum+=numbers;
            total=sum+numbers;
        }
        System.out.println("The grand total is: " +total);

    }

}

最佳答案

下面的程序将要求用户首先分别插入行数和列数。接下来,使用嵌套的 for 循环要求用户在每行中插入每列的值。

第一个 For 循环迭代行数。对于每次迭代,第二个 For 循环将迭代输入的列数。因此要求用户为每列输入一个值。

每行输入的值的总和将由 sumOfRow 计算。最后,这些值将相加并显示最终总计。

希望这有帮助:)

import java.util.Scanner;
public class tableintegers {

    public static void main(String[] args) {

        Scanner input=new Scanner(System.in);

        System.out.print("Enter the number of rows:");
        int rows=input.nextInt();
        System.out.print("Enter the number of columns:");
        int cols=input.nextInt();

        int total=0, sumOfRow=0, numbers=0;
        for(int i=0; i<rows; i++) {
            sumOfRow = 0;
            System.out.println("\nRow No. " + (i + 1) );
            for(int j=0; j<cols; j++) {
                System.out.print("Enter value for Column " + (j+1) + ": ");
                numbers = input.nextInt();
                sumOfRow += numbers;
            }
            System.out.println("Sum of Row No. " + (i+1) + " Values: " + sumOfRow);
            total += sumOfRow;
        }
        System.out.println("\nThe grand total is: " +total);

    }

}

关于java - 需要帮助嵌套 for 循环来添加 java 中表中的所有行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58780577/

相关文章:

java - JSTL 在尝试访问 bean 时给出错误

java - 无法从 Android 手机访问 pdf 中的链接

java - 当 isNameSpaceAware 和 isValidating 为 "Node"时,XPath 为 "true"返回 null

java - 嵌套 for-while 循环超出时间限制

java - 将 boolean 方法从另一个类连接到 main

java - 无法解析方法,为什么?

java - 如何在Java中创建通用数组?

java - 重构 - 简化 java 中的嵌套 for 循环

python - 是否可以在python中为命令应用for循环

ruby-on-rails - 使 Controller 方法可供查看,但略有不同?