如何在Java中对每行数据剔除最大值和最小值
Solution: Remove Max and Min from Each Row in Java
Alright, let's build on your existing code to implement the functionality of removing the maximum and minimum values from each row of your 2D array. I'll walk you through the steps and provide a complete, working version of the code.
First, let's fix a small gap in your original code: the empty exception handling makes debugging nearly impossible. I'll add basic error logging to help catch file-reading issues.
Complete Code Implementation
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Average { static Integer[][] myDouble = new Integer[10][12]; static int x = 0, y = 0; public Average() { // Use try-with-resources to auto-close the reader (safer than manual close) try (BufferedReader in = new BufferedReader(new FileReader("StudentIdAverage.txt"))) { String line; while ((line = in.readLine()) != null) { String[] values = line.split("\\s+"); for (String str : values) { int strDouble = Integer.parseInt(str); myDouble[x][y] = strDouble; y++; } x++; y = 0; } } catch (IOException ioException) { // Add meaningful error logging System.err.println("Failed to read the file: " + ioException.getMessage()); ioException.printStackTrace(); } } // Core method to process each row: remove one max and one min value public Integer[][] processRows() { // Each row loses 2 elements, so new array is 10x10 Integer[][] processedArray = new Integer[10][10]; for (int row = 0; row < myDouble.length; row++) { Integer[] currentRow = myDouble[row]; if (currentRow == null) continue; // Step 1: Find max and min values in the current row int max = currentRow[0]; int min = currentRow[0]; for (int num : currentRow) { if (num > max) max = num; if (num < min) min = num; } // Step 2: Collect elements, skipping one max and one min List<Integer> filteredElements = new ArrayList<>(); boolean removedMax = false; boolean removedMin = false; for (int num : currentRow) { // Skip first occurrence of max if (num == max && !removedMax) { removedMax = true; continue; } // Skip first occurrence of min if (num == min && !removedMin) { removedMin = true; continue; } filteredElements.add(num); } // Convert list back to array for the result processedArray[row] = filteredElements.toArray(new Integer[0]); } return processedArray; } // Test the functionality with a main method public static void main(String[] args) { Average processor = new Average(); Integer[][] result = processor.processRows(); // Print processed rows to verify for (Integer[] row : result) { for (int num : row) { System.out.print(num + " "); } System.out.println(); } } }
Key Details Explained
- Safer File Handling: The try-with-resources block automatically closes the
BufferedReader, eliminating the risk of resource leaks from forgottenclose()calls. - Max/Min Detection: We loop through each row once to find the highest and lowest values—this is efficient and avoids unnecessary iterations.
- Selective Filtering: We only remove the first occurrence of the max and min values (even if duplicates exist). If you need to remove all instances of max/min instead, simplify the filtering logic to:
if (num != max && num != min) { filteredElements.add(num); } - Result Structure: The processed array uses a 10x10 structure since each original row (12 elements) loses exactly two values.
Quick Note
Ensure your StudentIdAverage.txt file has exactly 10 lines, each with 12 whitespace-separated integers. If your file has variable line lengths, add extra checks to avoid ArrayIndexOutOfBoundsException.
内容的提问来源于stack exchange,提问作者john john
相关产品推荐
相关产品推荐

