Here you can find the source of arraySum(int[] intArray, short flag)
Parameter | Description |
---|---|
intArray | the integers to calculate the sum of |
flag | this flag is meant to check if all elements in the array must be positive (0), negative(1), or it doesn't matter (anything else) |
Parameter | Description |
---|---|
IllegalArgumentException | if precondition is violated |
public static int arraySum(int[] intArray, short flag)
//package com.java2s; //License from project: Open Source License public class Main { /**/* w w w . j a v a2 s.c o m*/ * Returns the sum of the values of all integer elements in an integer array * * @param intArray the integers to calculate the sum of * @param flag this flag is meant to check if all elements in the array must * be positive (0), negative(1), or it doesn't matter (anything else) * @pre * {@code (flag != 0 && flag != 1) || (flag == 0 && (\forall i; intArray.has(i); i >= 0)) || (flag == 1 && (\forall i; intArray.has(i); i <= 0))} * @throws IllegalArgumentException if precondition is violated * @return {@code sum(i = 0; intArray.has(i); intArray[i]) } */ public static int arraySum(int[] intArray, short flag) { int r = 0; for (int i : intArray) { //check flag if (flag == 0 && i < 0) { // throw new IllegalArgumentException( "all integers in array must be positive"); } else if (flag == 1 && i > 0) { // throw new IllegalArgumentException( "all integers in array must be negative"); } r += i; } return r; } }