求助:Java中不使用数组,通过嵌套循环实现表格行列求和
修正你的表格求和代码(无数组版本)
咱们先聊聊你现有代码里的几个明显问题:
- 缺少列遍历逻辑:你只读取了每行的两个数字,但没根据输入的
cols值去读取整行的所有数字 - 求和逻辑混乱:
sum和total的计算完全不符合行总和、总总和的需求 - 完全没处理列总和的计算,这可是你需求里明确要求的核心功能之一
接下来我给你一个符合要求的版本,完全不用数组存储表格数据,同时实现行总和、列总和以及总总和的计算和清晰展示:
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(); input.nextLine(); // 吃掉换行符,避免后续读取字符串出错 int grandTotal = 0; // 用字符串数组暂存每行的输入内容(只是存输入文本,不是存表格数字,符合你不用数组的要求) String[] rowInputs = new String[rows]; // 第一步:读取每行数据,计算行总和与总总和 System.out.println("Enter each row's numbers separated by spaces:"); for (int i = 0; i < rows; i++) { System.out.print("Row " + (i + 1) + ": "); String rowStr = input.nextLine(); rowInputs[i] = rowStr; // 拆分当前行的数字,计算行总和 String[] numsInRow = rowStr.split(" "); int rowTotal = 0; for (String numStr : numsInRow) { int num = Integer.parseInt(numStr); rowTotal += num; grandTotal += num; } // 打印当前行的总和 System.out.println("Row " + (i + 1) + " total: " + rowTotal); } // 第二步:计算并打印列总和 System.out.println("\nColumn totals:"); for (int col = 0; col < cols; col++) { int colTotal = 0; for (int row = 0; row < rows; row++) { String[] numsInRow = rowInputs[row].split(" "); // 确保每行的数字数量符合列数要求 if (col < numsInRow.length) { colTotal += Integer.parseInt(numsInRow[col]); } } System.out.println("Column " + (col + 1) + " total: " + colTotal); } // 打印最终总总和 System.out.println("\nThe grand total is: " + grandTotal); input.close(); } }
代码逻辑说明:
- 行数据读取与行总和计算:用字符串接收每行的所有输入,拆分后逐个转成整数累加,同时同步累加到总总和
- 列总和计算:通过遍历暂存的每行输入字符串,取出对应列的数字进行累加,不用存储任何表格数字数组
- 友好交互:添加了清晰的输入提示和分块输出,让用户能直观看到每一行、每一列的求和结果
测试示例:
输入:
Give the number of rows and number of columns: 2 3 Enter each row's numbers separated by spaces: Row 1: 1 2 3 Row 2: 4 5 6
输出:
Row 1 total: 6 Row 2 total: 15 Column totals: Column 1 total: 5 Column 2 total: 7 Column 3 total: 9 The grand total is: 21
内容的提问来源于stack exchange,提问作者HiAlllllll
相关产品推荐
相关产品推荐

