Using BlueJ Program ArrayList and Loops Create a class named Loops and do the fo
ID: 3772015 • Letter: U
Question
Using BlueJ Program
ArrayList and Loops Create a class named Loops and do the following:
Create an ArrayList named Contacts and fill with the following Names: John, Maria, Matt, Chris, Jen (in this order).
Write three methods to process the ArrayList using each of the three loop types: for, foreach and while. The methods should be written so that they will still accurately process the ArrayList even after items are added or removed. You will need to create and populate the ArrayList before using the methods to process it. Running any of the loop methods will produce a listing of the names from the ArrayList.
Explanation / Answer
import java.util.ArrayList;
import java.util.List;
/**
*
*/
/**
* @author Srinivas Palli
*
*/
public class Loop {
List<String> Contacts = new ArrayList<String>();
/**
* Adding Faculty Names
*/
public Loop() {
// TODO Auto-generated constructor stub
// John, Maria, Matt, Chris, Jen
}
/**
* display using for loop
*/
public void displayUsingFor() {
for (int i = 0; i < Contacts.size(); i++) {
String facultyName = Contacts.get(i);
System.out.println(" " + (i + 1) + ") " + facultyName);
}
}
/**
* display using for each loop
*/
public void displayUsingForEach() {
int i = 0;
for (String facultyName : Contacts) {
System.out.println(" " + ((i++) + 1) + ") " + facultyName);
}
}
/**
* display using while loop
*/
public void displayUsingWhile() {
int i = 0;
while (i < Contacts.size()) {
String facultyName = Contacts.get(i);
System.out.println(" " + ((i++) + 1) + ") " + facultyName);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Loop loop = new Loop();
System.out.println("Calling displayUsingFor():");
loop.displayUsingFor();
loop.Contacts.add("Joan");
loop.Contacts.add("Maria");
System.out.println("Calling displayUsingForEach():");
loop.displayUsingForEach();
loop.Contacts.add("Matt");
loop.Contacts.add("Chris");
loop.Contacts.add("Jen");
System.out.println("Calling displayUsingWhile():");
loop.displayUsingWhile();
}
}
OUTPUT:
Calling displayUsingFor():
Calling displayUsingForEach():
1) Joan
2) Maria
Calling displayUsingWhile():
1) Joan
2) Maria
3) Matt
4) Chris
5) Jen
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.