java - 为什么我收到此错误 : data structures (arrays)?

标签 java arrays structure

我基本上需要找到总和为负的子数组的数量。

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

最佳答案

这是因为这里变量j的范围。当您在映射中引用变量时,JVM 会尝试初始化它。在您的情况下,JVM 正在尝试使用映射的内容初始化 j,但此时它已经在第二个 for 循环中可用。只需使用任何其他变量(例如“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);

}
}

关于java - 为什么我收到此错误 : data structures (arrays)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51896302/

相关文章:

java - Android LocalSocket 在阻塞读取时不会关闭

java - 如何使用旧版本的 hibernate 运行 Spring boot

python - IndexError : too many indices. 1 行 2 列的 Numpy 数组

c - 指针/结构

c - 我们什么时候不应该使用#pragma pack?

java - XML 和 DOM 获取#text 输出

java - Java 中 8x8 网格的广度优先搜索

java - 在Java Map <Integer, Double[]>中,是否需要在获取和修改后放置Double[]?

java - 为什么我收到的文档未包含在投影中?

c - 在 C 中使用结构访问数组