public class FindIndex { public static void main(String[] args) { // TODO 自动生成的方法存根 int[] array=new int[] {1,4,8,22,14,5,2,7}; public int[][] qiuhe(int[]array,int target){ int k=0; int[][] a=new int[2][array.length]; for(int i=0;i<array.length;i++){ for(int j=i+1;j<array.length;j++){ if(array[i]+array[j]==target) { a[0][k]=i; a[1][k++]=j; } } } return a; } }
时间: 2023-11-14 22:06:35 浏览: 44
这段代码有几个问题,无法编译通过:
1. `public int[][] qiuhe(int[]array,int target)` 这个方法应该是在类的外部定义的,而不是在 `main` 方法内部定义的。
2. 方法的定义缺少右大括号 `}`。
3. `int[][] a=new int[2][array.length];` 这行代码应该放在方法的开头,而不是在 `for` 循环中。
下面是修改后的代码:
```
public class FindIndex {
public static void main(String[] args) {
int[] array = new int[] {1, 4, 8, 22, 14, 5, 2, 7};
int target = 9;
int[][] result = qiuhe(array, target);
for (int i = 0; i < result[0].length; i++) {
if (result[0][i] == 0 && result[1][i] == 0) {
break;
}
System.out.println("Index 1: " + result[0][i] + ", Index 2: " + result[1][i]);
}
}
public static int[][] qiuhe(int[] array, int target) {
int k = 0;
int[][] a = new int[2][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] + array[j] == target) {
a[0][k] = i;
a[1][k++] = j;
}
}
}
return a;
}
}
```
这个程序的功能是在给定数组中找到两个数的索引,使得它们的和等于给定的目标值。程序的输出应该是:
```
Index 1: 0, Index 2: 7
Index 1: 1, Index 2: 6
Index 1: 3, Index 2: 4
Index 1: 5, Index 2: 7
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)