Java技术问询:如何用for-each循环、不使用算术运算符实现二维数组行求和并返回一维数组
Got it, let's work through this problem to meet your requirements. First, we need to fix the sumArr method to remove the + operator, then build the outer method that processes the 2D array using only for-each loops.
Step 1: Improve the sumArr Method
The issue with your current sumArr is the direct use of the + arithmetic operator. We can replace this with Integer.sum(), a static method from Java's Integer class that calculates the sum of two integers—no manual arithmetic operators needed, and we keep the for-each loop intact.
Here's the revised method:
public static int sumArr(int[] m) { int sum = 0; for (int number : m) { // Use Integer's built-in sum method instead of direct + operator sum = Integer.sum(sum, number); } return sum; }
Step 2: Build the 2D Array Row Sum Method
Next, we need a method that takes your 2D array, iterates over each row with a for-each loop, calculates each row's sum using our revised sumArr, and returns the result as a 1D array. We have two clean approaches here:
Approach 1: Using ArrayList to Avoid Index Arithmetic
This approach uses a collection to collect sums, so we don't need to manually manage an index (which would require arithmetic operators like ++):
import java.util.ArrayList; import java.util.List; public static int[] getRowSums(int[][] t) { List<Integer> rowSumsList = new ArrayList<>(); // Iterate over each row with for-each loop for (int[] row : t) { rowSumsList.add(sumArr(row)); } // Convert the list to an int array (no arithmetic operators used here) return rowSumsList.stream().mapToInt(Integer::intValue).toArray(); }
Approach 2: Using a Direct Array with Safe Index Increment
If you prefer working directly with arrays instead of collections, we can use Integer.sum() to increment our index (avoiding the ++ arithmetic operator):
public static int[] getRowSums(int[][] t) { int[] rowSums = new int[t.length]; int index = 0; for (int[] row : t) { rowSums[index] = sumArr(row); // Increment index without using ++ index = Integer.sum(index, 1); } return rowSums; }
Test the Solution
You can test either approach with a sample 2D array to verify it works:
public static void main(String[] args) { int[][] testArray = {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}}; int[] results = getRowSums(testArray); // Print the results (using for-each loop, of course) for (int sum : results) { System.out.println(sum); // Output: 6, 9, 30 } }
Both approaches strictly follow your rules: no arithmetic operators are used in our code, and we only rely on for-each loops for iteration.
内容的提问来源于stack exchange,提问作者MontyLemons

