java为什么会出现这些错误?表达式的非法开始
这是我的密码:
public class JavaApplication16 {
public static void main(String[] args) {
//illegal start of expression, ']' expected, <identifier> expected
boolean a = groupSum(0, [2,4,8], 10);
}
public boolean groupSum(int start, int[] nums, int target) {
if (start >= nums.length) return (target == 0);
if (groupSum(start + 1, nums, target - nums[start])) return true;
if (groupSum(start + 1, nums, target)) return true;
return false;
}
}
我试着想办法解决这个问题,但我真的很迷茫。请帮我调试代码
# 1 楼答案
下面是使用int数组的正确方法
# 2 楼答案
您需要将代码更改为如下所示
1-
new int[]{2,4,8}
创建整数数组2-将groupSum方法更改为静态或创建对象形式
JavaApplication16
,如下所示JavaApplication16 ja16= new JavaApplication16(); ja16.groupSum(...);
您可以执行以下操作来解决问题
# 3 楼答案
必须将int数组定义为
另外,方法
groupSum
是一个实例方法,而main是一个静态方法;不能在静态方法中使用实例方法您有两种解决方案:
groupSum
方法定义为静态李>创建类的对象
JavaApplication16
并使用其方法。 代码如下:# 4 楼答案
您没有使用正确的符号来创建数组。创建一个int数组看起来像:
new int[]{1, 2, 3}.
代码中存在的另一个问题是,您正在从静态上下文调用一个非静态方法。您可以通过将groupSum
标记为静态来解决这个问题。 以下是您的代码的固定版本: