You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组条件筛选赋值异常求助:按顺序填充数组时出现错误

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 r is initialized to 0 inside the if block, so every time you find a matching element, you overwrite array[0] instead of moving to the next position.
  • Fixed Array Length Risk: Initializing array to length 10 is risky—if there are more than 10 matching elements, you'll get an ArrayIndexOutOfBoundsException; if fewer, you'll have unused zero-filled slots.
  • Missing Return Statement: Your method declares it returns an int[], but there's no return statement 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:59:15