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

调用twoSum方法时出现misplaced constructs与variableDeclarator expected错误求助

问题分析与修复

直接触发编译错误的调用问题

你调用twoSum时的数组参数语法不符合Java规范——不能直接用{元素列表}作为方法的数组参数,必须显式声明数组类型,正确写法是new int[]{2,7,11,15}。

错误调用代码:

int arr[] = obj.twoSum({2,7,11,15},9);

修正后的调用代码:

int arr[] = obj.twoSum(new int[]{2,7,11,15},9);

代码中其他致命问题

除了调用错误,twoSum方法还有两个会导致运行时崩溃的问题:

  • output初始化为null,找到目标值时直接给output[0]、output[1]赋值会触发空指针异常,需要先初始化数组:int[] output = new int[2];
  • 循环条件i <= nums.length-1会导致数组越界:当i等于数组最后一个索引时,i+1超出数组最大索引范围,需将循环条件改为i < nums.length-1

修复后的完整代码

public class Sumofint {
    public int[] twoSum(int[] nums, int target) {
        int total = 0; 
        int[] output = new int[2]; // 初始化结果数组
        // 修改循环条件避免数组越界
        for(int i = 0; i < nums.length - 1; i++){
            total = nums[i] + nums[i+1];
            if (total == target){
                output[0] = i;
                output[1] = i+1;
                // 找到结果后直接返回,无需继续循环
                return output;
            }
        }
        // 未找到匹配时可抛出异常或返回默认值,按需调整
        throw new IllegalArgumentException("No two consecutive elements sum to target");
    }
    public static void main(String []args) {
        Sumofint obj = new Sumofint();
        int arr[] = obj.twoSum(new int[]{2,7,11,15},9);
        System.out.println(arr[0]+", " + arr[1]);
    }
}

内容的提问来源于stack exchange,提问作者Rajiv Pahuja

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:12:39