The following code is supposed to fil list3 with every possible sum of elements
ID: 3575901 • Letter: T
Question
The following code is supposed to fil list3 with every possible sum of elements from list1 and list2. So list3 should end up holding
{ 11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 42, 43, 51, 52, 53}
But the code is incorrect. What is wrong? How could you fix it?
List<Integer> list1 = Arrays.asList(10,20, 30, 40, 50);
List<Integer> list2 = Arrays.asList(1, 2, 3);
List<Integer> list3 = new ArrayList<Interger>();
for (Iterator<Integer> it1 = list1.iterator(); it1.hasNext(); )
for (Iterator<Integer> it2 = list2.iterator(); it2.hasNext(); )
{
int n = it1.next();
int m = it2.next();
list3.add( n + m );
}
for (int i : list3)
System.out.print(i + " ");
System.out.println();
Explanation / Answer
//Import packages
import java.util.ArrayList;
import java.util.List;
//Begin class
public class Test {
public static void main(String[] args) { //begin main method
//Array list declarations
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
List<Integer> list3 = new ArrayList<Integer>();
//adding list elements
list1.add(10);
list1.add(20);
list1.add(30);
list1.add(40);
list1.add(50);
list2.add(1);
list2.add(2);
list2.add(3);
//loop to find summation and add to list3
for (int i = 0; i < list1.size(); i++)
{
for (int j = 0; j < list2.size(); j++)
{
list3.add(list1.get(i) + list2.get(j));
}
}
//list2 elements display after performing sum task
for (int i : list3)
System.out.print(i + " ");
System.out.println();
}
}
Output : 11 12 13 21 22 23 31 32 33 41 42 43 51 52 53
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.