Answer the question
In order to leave comments, you need to log in
How to create a method for finding the sum of array elements in Java and call it on different arrays?
In the problem of counting the queue service time from an arbitrary client at N cash desks, the queue is specified by an array of integers int[] customers, where each element customers[i] is the service time of the i-th client.
In the process of solving, it was necessary to sum the elements of the array in the case when we have N=1:
.........
} else if (n == 1) {
for (int i = 0; i < customers.length; i++ ) {
sum += customers[i];
}
}
.........
return sum;
public int sumOfArray(int ary[]) {
int s = 0;
for (int i = 0; i < ary.length; i++) {
s += ary[i];
}
return s;
}
Answer the question
In order to leave comments, you need to log in
If I understand correctly and you need the sum of the elements of three arrays, then:
Or you can create a method with varargs that will calculate the sum of an arbitrary number of arrays:
public int sumOfArray(int[]... ary) {
/// your code
}
int sumOfAll = IntStream.of(arr1).sum() + IntStream.of(arr2).sum() + IntStream.of(arr3).sum();
I do this now
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("4");
list.add("1");
int summ = list.stream()
.map(s -> Integer.parseInt(s)) // перевод из String в int
.reduce( (s1,s2) -> s1 + s2 ) // сумма
.orElse(0); // значение по умолчанию
System.out.println(summ);
public class Reduce {
public static class Offer {
int price;
public Offer (int price) {
this.price = price;
}
public int getPrice() {
return price;
}
}
public static void main(String args[]) {
List< Offer > list = new ArrayList<>();
list.add(new Offer(1));
list.add(new Offer(2));
list.add(new Offer(4));
list.add(new Offer(1));
int summ = list.stream()
.map(Offer::getPrice) // взять прайс
.reduce( (s1,s2) -> s1 + s2 ) // сумма
.orElse(0); // значение по умолчанию
System.out.println(summ);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question