猿问

为什么我会收到此错误:数据结构(数组)?

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


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


蝴蝶不菲
浏览 247回答 2
2回答

胡说叔叔

此行声明了一个变量j,该变量已在该范围内声明为循环计数器:int slice[] = IntStream.range(j, j + i + 1).map(j -> arr[j]).toArray();你必须给它一个不同的名字来摆脱这个编译错误:for (int i = 0; i < n; ++i) {&nbsp; &nbsp; // this is where j is defined for the loop scope&nbsp; &nbsp; for (int j = 0; j < n - i; ++j) {&nbsp; &nbsp; &nbsp; &nbsp; // replace the j inside the .map(...)&nbsp; &nbsp; &nbsp; &nbsp; int slice[] = IntStream.range(j, j + i + 1).map(s -> arr[s]).toArray();&nbsp; &nbsp; &nbsp; &nbsp; if (add(slice) < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ++count;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答