Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

You can also use a while or for loop to process list elements using the index. The ArrayList index starts at 0 just like arrays,

You can also use a while or for loop to process list elements using the index. The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use the get(index) to get the value at the index and set(index,value) to set the element at an index to a new value. If you try to use an index that is outside of the range of 0 to the number of elements 1 in an ArrayList, your code will throw an ArrayIndexOutOfBoundsException, just like in arrays.

importjava.util.*;

publicclassTestForLoop

{

publicstaticvoidmain(String[]args)

{

ArrayListmyList=newArrayList();

myList.add(50);

myList.add(30);

myList.add(20);

inttotal=0;

for(inti=0;i<=myList.size();i++)

{

total=total+myList.get(i);

}

System.out.println(total);

}

}

Question 2. What does the following code do? Guess before you run it. Then, add another enhanced for each loop that computes the product of all the elements in myList by multiplying them. Print out the product after the new loop. importjava.util.*; //importallclassesinthispackage.

publicclassTest1

{

publicstaticvoidmain(String[]args)

{

ArrayListmyList=newArrayList();

myList.add(50);

myList.add(30);

myList.add(20);

inttotal=0;

for(Integervalue:myList)

{

total+=value;

}

System.out.println("Sumofallelements:"+total);

//Writeafor-eachloopthatcomputestheproduct

//ofalltheelementsinmyListandprintouttheproduct.

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Financial management theory and practice

Authors: Eugene F. Brigham and Michael C. Ehrhardt

12th Edition

978-0030243998, 30243998, 324422695, 978-0324422696

Students also viewed these Programming questions