45.2k views
3 votes
Create a static method that: - is called appendPosSum - returns an ArrayList - takes one parameter: an ArrayList of Integers This method should: - Create a new ArrayList of Integers - Add only the positive Integers to the new ArrayList - Sum the positive Integers in the new ArrayList and add the Sum as the last element For example, if the incoming ArrayList contains the Integers (4,-6,3,-8,0,4,3), the ArrayList that gets returned should be (4,3,4,3,14), with 14 being the sum of (4,3,4,3). The original ArrayList should remain unchanged.

User Dietmar
by
6.7k points

1 Answer

6 votes

Answer:

The method in Java is as follows:

public static ArrayList<Integer> appendPosSum(ArrayList<Integer> nums) {

int sum = 0;

ArrayList<Integer> newArr = new ArrayList<>();

for(int num : nums) {

if(num>0){

sum+=num;

newArr.add(num); } }

newArr.add(sum);

return newArr;

}

Step-by-step explanation:

This defines the method; it receives an integer arraylist as its parameter; nums

public static ArrayList<Integer> appendPosSum(ArrayList<Integer> nums) {

This initializes sum to 0

int sum = 0;

This declares a new integer arraylist; newArr

ArrayList<Integer> newArr = new ArrayList<>();

This iterates through nums

for(int num : nums) {

If current element is greater than 0

if(num>0){

This sum is taken

sum+=num;

And the element is added to newArr

newArr.add(num); } }

At the end of the iteration; this adds the calculated sum to newArr

newArr.add(sum);

This returns newArr

return newArr;

}

User Victor Bocharsky
by
6.7k points