Wildcards
Completed
Write static double sum(List<? extends Number> nums) and use it on a List<Integer> and a List<Double>. Print both sums with 2 decimals.
Input
Line 1: integers. Line 2: decimals.
Output
Two lines.
Example
Input
1 2 3 0.5 0.25
Output
6.00 0.75
Editor
Java
Hints
A List<Integer> is NOT a List<Number>, but it is a List<? extends Number>.
Solution explanation
? extends lets a method read from lists of any subtype ("producer extends").
Show solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
static double sum(List<? extends Number> nums) {
double total = 0;
for (Number n : nums) {
total += n.doubleValue();
}
return total;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
for (String t : sc.nextLine().trim().split("\\s+")) {
ints.add(Integer.parseInt(t));
}
List<Double> doubles = new ArrayList<Double>();
for (String t : sc.nextLine().trim().split("\\s+")) {
doubles.add(Double.parseDouble(t));
}
System.out.printf("%.2f%n", sum(ints));
System.out.printf("%.2f%n", sum(doubles));
}
}