gpt4 book ai didi

Java "error: illegal start of type"抛出 IllegalArgumentException 时

转载 作者:行者123 更新时间:2023-12-02 12:17:53 26 4
gpt4 key购买 nike

我正在尝试用 Java 编写一个(强力)解决方案来解决二和问题:

import java.lang.*;

public class TwoSum {
public 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");
}

但是,当我尝试编译它时,出现以下错误:

/home/kurt/Documents/Algorithms/TwoSum.java:13: error: illegal start of type
throw new IllegalArgumentException("No two sum solution");
^
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: ';' expected
throw new IllegalArgumentException("No two sum solution");
^
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: invalid method declaration; return type required
throw new IllegalArgumentException("No two sum solution");
^
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: illegal start of type
throw new IllegalArgumentException("No two sum solution");
^
4 errors
[Finished in 0.8s with exit code 1]

我有点困惑可能是什么导致了这个错误? (我从示例片段中获取了代码,但没有注意到任何差异)。

最佳答案

使用以下代码:

import java.lang.*;

public class TwoSum {
public 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");
}
}

在这种情况下, throw new IllegalArgumentException("Notwo sum Solution");在方法内部。

关于Java "error: illegal start of type"抛出 IllegalArgumentException 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46021888/

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