The following code is supposed to fil list3 with every possible sum of elements
ID: 3581444 • 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 following code is incorrect. What is wrong? How could you fix it?
List list1 = Arrays.asList(10,20, 30, 40, 50);
List list2 = Arrays.asList(1, 2, 3);
List list3 = new ArrayList();
for (Iterator it1 = list1.iterator(); it1.hasNext(); )
for (Iterator 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
Hi
I have fixed the code and highlighted the code changes below. Issue here is that we are iterating list1 elements inside list2 iterator. Since list2 elements less than list1 elements, it will throw an exception NoSuchElementException. And also we need to add list1 each element wth all elements of list2. When we use next() method it will give each element from the list. So int n = it1.next(); this statement should be out side of list2 iterator.
List<Integer> list1 = Arrays.asList(10,20, 30, 40, 50);
List<Integer> list2 = Arrays.asList(1, 2, 3);
List<Integer> list3 = new ArrayList();
for (Iterator<Integer> it1 = list1.iterator(); it1.hasNext(); ){
int n = it1.next();
for (Iterator<Integer> it2 = list2.iterator(); it2.hasNext(); )
{
int m = it2.next();
list3.add( n + m );
}
}
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.