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

Java静态twoSum方法实现报错求助:方法twoSum(String)未定义

代码错误排查与修正

核心错误点梳理

  • 方法定义语法错误
    原方法public int[] static twoSum(new int[], int)完全不符合Java语法规范:

    • 静态方法的修饰符顺序必须是static在前,正确写法为public static int[] twoSum(int[] nums, int target)
    • 参数不能用new int[]这种写法,必须明确指定参数类型和参数名称,比如int[] nums(数组参数)和int target(目标值参数)
  • 方法调用逻辑混乱
    main方法中的调用twoSum(scan.nextLine()).split(" ")存在两处致命问题:

    • twoSum方法需要接收int[]和int类型参数,你直接传入了String类型的输入内容,还错误地链式调用split方法,完全不符合方法的参数要求
    • System.out.println不支持逗号分隔多个参数,写法本身违反语法
  • 变量未定义与拼写错误

    • 方法内使用的str_arr从未定义,应替换为传入的int数组参数(比如命名为nums)
    • 返回语句中的reult是拼写错误,正确应为result
  • 静态方法调用权限问题
    main是静态方法,直接调用非静态的twoSum会报错,必须将twoSum声明为static方法(符合你要求的静态实现)

  • Scanner输入处理bug
    使用scan.nextLine()后直接调用scan.nextInt()会残留换行符,导致目标值读取失败,需要额外处理换行符


修正后的完整代码

import java.util.Scanner;

class Solutiontest1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        // 读取输入的数字字符串,分割后转换为int数组
        String[] strNums = scan.nextLine().split(" ");
        int[] nums = new int[strNums.length];
        for (int i = 0; i < strNums.length; i++) {
            nums[i] = Integer.parseInt(strNums[i]);
        }
        
        // 读取目标值,处理换行符残留问题
        int target = scan.nextInt();
        scan.nextLine();
        
        // 调用静态twoSum方法
        int[] result = twoSum(nums, target);
        
        // 格式化输出结果
        System.out.println("[" + result[0] + ", " + result[1] + "]");
        scan.close();
    }

    // 符合规范的静态twoSum方法实现
    public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        // 双层循环查找两数之和等于目标值的索引
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    // 找到结果后直接返回,减少不必要的遍历
                    return result;
                }
            }
        }
        // 未找到符合条件的组合时返回默认数组(可根据需求修改为抛出异常)
        return result;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:34:56