简体   繁体   English

size() 正在打印多次

[英]size() is printing multiple times

I am trying to figure out why the arr.size() is printing multiple times (the same number as the size).我试图弄清楚为什么 arr.size() 打印多次(与大小相同的数字)。

I'm supposed to take an array and state, to an accuracy of 6 decimal places, what portion of the array is positive, negative, or zero.我应该取一个数组和 state,精确到小数点后 6 位,数组的哪个部分是正数、负数或零。 But, I can't seem to get past the multiple lines printing.但是,我似乎无法通过多行打印。

class Result {

    public static void plusMinus(List<Integer> arr) {
        int plus = 0;
        int minus = 0;
        int zero = 0;
    
        for (int i = 0; i < arr.size(); ++i) {
            if (i == 0) {
                zero++;
            } else if (i < 0) {
                minus++;
            } else if (i > 0) {
                plus++;
            }
        
        double plusPortion = plus / arr.size();
        double minusPortion = minus / arr.size();
        double zeroPortion = zero / arr.size();
        
        System.out.println(arr.size());
        //System.out.println(plusPortion);
        //System.out.println(minusPortion);
        //System.out.println(zeroPortion);
        }
        
        
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        Result.plusMinus(arr);

        bufferedReader.close();
    }
}

The Solution class was provided as part of the challenge.解决方案 class 作为挑战的一部分提供。

Move size printing and portion calculation outside the loop, like this:将尺寸打印和部分计算移到循环之外,如下所示:

public static void plusMinus(List<Integer> arr) {
    int plus = 0;
    int minus = 0;
    int zero = 0;

    for (int i = 0; i < arr.size(); ++i) {
        if (i == 0) {
            zero++;
        } else if (i < 0) {
            minus++;
        } else if (i > 0) {
            plus++;
        }
    }
    //calculate portions
    double plusPortion = plus / arr.size();
    double minusPortion = minus / arr.size();
    double zeroPortion = zero / arr.size();
    //log results
    System.out.println("Array size:" + arr.size());
    //System.out.println(plusPortion);
    //System.out.println(minusPortion);
    //System.out.println(zeroPortion);   
}

You need to make 'calculations' in the for loop, then print the results.您需要在 for 循环中进行“计算”,然后打印结果。 In the code you posted, you were printing results for each step/element of the list.在您发布的代码中,您正在为列表的每个步骤/元素打印结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM