我基本上需要找到总和为负的子数组的数量。
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 error
Exit Status
255
答案 0 :(得分:1)
这是因为此处的变量j
的范围。当您在map中引用变量时,JVM会尝试对此进行初始化。在您的情况下,JVM尝试使用映射的内容初始化j,但是从第二个for循环开始,JVM那时已经可用。只需使用其他任何变量(例如“ k”)即可完成操作。
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(k -> arr[k]).toArray();
if(add(slice) < 0)
{
++count;
}
}
}
System.out.println(count);
}
}
答案 1 :(得分:0)
此行声明一个变量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;
}
}
}