I am trying to figure out why the arr.size() is printing multiple times (the same number as the 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. 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.
>Solution :
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. In the code you posted, you were printing results for each step/element of the list.