我基本上需要找到总和为负的子数组的数量。import java.io.*;import java.util.stream.IntStream;import java.util.Arrays;import java.util.Scanner;public class Solution { static int add(int a[]) { int sum = 0; for (int i = 0; i < a.length; ++i) { sum = sum + a[i]; } return sum; } public static void main(String[] args) { /* * Enter your code here. * Read input from STDIN. * Print output to STDOUT. * Your class should be named Solution. */ int count = 0; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int k = 0; k < n; ++k) { arr[k] = sc.nextInt(); } for (int i = 0; i < n; ++i) { for (int j = 0; j < n - i; ++j) { int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray(); if (add(slice) < 0) { ++count; } } } System.out.println(count); }}编译消息Solution.java:32: error: variable j is already defined in method main(String[])int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray(); ^1 errorExit Status255
2 回答
胡说叔叔
TA贡献1804条经验 获得超8个赞
此行声明了一个变量j,该变量已在该范围内声明为循环计数器:
int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();
你必须给它一个不同的名字来摆脱这个编译错误:
for (int i = 0; i < n; ++i) {
// this is where j is defined for the loop scope
for (int j = 0; j < n - i; ++j) {
// replace the j inside the .map(...)
int slice[] = IntStream.range(j, j + i + 1).map(s -> arr[s]).toArray();
if (add(slice) < 0) {
++count;
}
}
}
添加回答
举报
0/150
提交
取消