Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.logging.Logger;
- public class Main {
- private static Logger logger;
- public static void main(String[] args) {
- System.out.println(customSumNumbers(true, -1));
- System.out.println(customSumNumbers(true, 1,2,3,4));
- System.out.println(customSumNumbers(true, 1,2,-3,-4));
- System.out.println(customSumNumbers(false, 1,2,-3,-4));
- System.out.println(customSumNumbers(true, -1,-1));
- System.out.println(computeAverage(1,2,3,4,5,6));
- System.out.println(computeAverage(1,2,-3,4,5,-6));
- }
- /**
- * Method to sum numbers in a custom way - either sum only positives either the negative ones
- * @param numbers variable length array of integer numbers to be processed
- * @return
- */
- private static int customSumNumbers(boolean sumOnlyPositives, int... numbers) {
- int sum = 0;
- int faultsCount = 0;
- for (int number : numbers) {
- if (sumOnlyPositives && number >= 0) {
- sum += number; // let's sum only the positives
- } else if (!sumOnlyPositives && number < 0) {
- sum += number; // let's sum only the negatives
- } else {
- faultsCount++; // current number is not considered since it is not valid according to the value of sumOnlyPositives flag
- }
- }
- if (faultsCount == numbers.length) {
- System.out.println("WARN | no numbers from the given list respect the sumOnlyPositives flag! Returning default 0 value.");
- }
- return sum;
- }
- private static double computeAverage (int... numbers) {
- return (double) (customSumNumbers(true, numbers) + customSumNumbers(false, numbers)) / (double) numbers.length;
- }
- }
Add Comment
Please, Sign In to add comment