In: Computer Science
Just that method --> Java code
Write a method “int sumPos(List aList)” to calculate the sum of positive integers in an ADT List aList of integers using ADT List operations.
ADT List operations: isEmpty(), size(), add(index, item), remove(index), get(index), and removeAll().
You should not assume how an ADT List is implemented.
Using array indexing, head/tail references, or any operation not defined in ADT List is not allowed.
The required method is given below:
//method to calculate the sum of positive integers
public static int sumPos(List aList)
{
//variable declarationa and initialization
int sum=0;
//check if the size of the list is zero
if(aList.size()==0)
return 0;
//calcuate the sum of the positive number
while(!aList.isEmpty())
{
if((int)aList.get(0)>0)
{
sum = sum + (int)aList.get(0);
}
aList.remove(0);
}
//return the sum
return sum;
}
The complete program source code including the above method for testing is given below:
import java.util.ArrayList;
import java.util.List;
public class Main
{
//method to calculate the sum of positive integers
public static int sumPos(List aList)
{
//variable declarationa and initialization
int sum=0;
//check if the size of the list is zero
if(aList.size()==0)
return 0;
//calcuate the sum of the positive number
while(!aList.isEmpty())
{
if((int)aList.get(0)>0)
{
sum = sum + (int)aList.get(0);
}
aList.remove(0);
}
//return the sum
return sum;
}
public static void main(String[] args)
{
//list declaration
List<Integer> aList = new
ArrayList<Integer>();
//add number to the list
aList.add(0, 5);
aList.add(1, 3);
aList.add(2, -3);
//method calling and display the result
System.out.println(sumPos(aList));
}
}
OUTPUT:
8