数组条件筛选赋值异常求助:按顺序填充数组时出现错误
Fixing Your Array Filtering Logic Issues
Let's break down the problems in your current code and fix them step by step:
Key Issues in the Original Code
- Wrong Condition Check: You need to filter elements where
b[i] > x OR b[i] < y, but your code uses&&(AND) which selects elements between x and y—completely opposite of your requirement. - Index Reset Bug: The variable
ris initialized to 0 inside the if block, so every time you find a matching element, you overwritearray[0]instead of moving to the next position. - Fixed Array Length Risk: Initializing
arrayto length 10 is risky—if there are more than 10 matching elements, you'll get anArrayIndexOutOfBoundsException; if fewer, you'll have unused zero-filled slots. - Missing Return Statement: Your method declares it returns an
int[], but there's noreturnstatement at the end, which will cause a compile error.
Corrected Code
public int[] method(int[] b, int x, int y) { // First, count how many elements meet the condition int count = 0; for (int num : b) { if (num > x || num < y) { count++; } } // Initialize array with the exact needed length int[] array = new int[count]; int r = 0; // Initialize index outside the loop to avoid resetting // Populate the array with matching elements for (int num : b) { if (num > x || num < y) { array[r] = num; r++; } } return array; // Return the populated array }
Explanation of Fixes
- Corrected Condition: Swapped
&&to||to match your requirement of elements greater than x or less than y. - Persistent Index: Moved
int r = 0;outside the loop so it increments continuously as we add elements, instead of resetting to 0 every time. - Dynamic Array Length: First counted the number of valid elements to create an array of exactly the right size—no more unused slots or out-of-bounds errors.
- Added Return Statement: The method now properly returns the filtered array as declared.
If you want to handle edge cases (like an empty input array b), this code already accounts for that—count will be 0, and we'll return an empty array, which is safe.
内容的提问来源于stack exchange,提问作者Maggie Blanton
相关产品推荐
相关产品推荐

