gpt4 book ai didi

java - 错误数组整数元素总和java

转载 作者:行者123 更新时间:2023-11-29 06:54:41 25 4
gpt4 key购买 nike

我在这里找不到错误提示:

class Ideone {
public static void main (String[] args) throws java.lang.Exception
{
twoSum({2,4,7},9);
}
public static int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}

错误是:

Main.java:12: error: illegal start of expression
twoSum({2,4,7},9);
^
Main.java:12: error: ';' expected
twoSum({2,4,7},9);
^
Main.java:12: error: illegal start of expression

我认为声明很好,那么如何更改才能使该功能起作用?

最佳答案

{2,4,7}只能用在数组的声明中,如:

int[] arr = {2,4,7};

要将这样的数组作为参数传递给方法,请使用

twoSum(new int[] {2,4,7},9);

关于java - 错误数组整数元素总和java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com