The purpose of this assignment is to prove that you can build and use an arrayli
ID: 3815939 • Letter: T
Question
The purpose of this assignment is to prove that you can build and use an arraylist.
Create a project named LastnameFirstnameHW7.
The purpose of your program is show that you can build and use an arraylist. The program will function a lot like Homework 6. The program should operate as follows:
Enter a name or 'Q' to quit: Tamaya
Enter a name or 'Q' to quit: Doug
Enter a name or 'Q' to quit: Lakshmi
Enter a name or 'Q' to quit: Q
The names you entered are: Tamaya, Doug, Lakshmi.
You must use a loop and an arraylist for this program. Assignments submitted without a loop and an arraylist will not be graded.
DO NOT use an array to complete this progam. You must create and use an arraylist.
Hint: it is easier to use a While loop than a For loop for this assignment.
Hint: you can use a boolean variable (see ArrayDemo.java example code) to keep track of whether to iterate your loop again
Explanation / Answer
LastnameFirstnameHW7.java
import java.util.ArrayList;
import java.util.Scanner;
public class LastnameFirstnameHW7 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> namesList = new ArrayList<String>();
System.out.print("Enter a name or 'Q' to quit: ");
String name = scan.next();
while(!name.equals("Q")) {
namesList.add(name);
System.out.print("Enter a name or 'Q' to quit: ");
name = scan.next();
}
System.out.print("The names you entered are: ");
for(int i=0; i<namesList.size(); i++) {
if(i == namesList.size()-1){
System.out.print(namesList.get(i)+".");
}
else {
System.out.print(namesList.get(i)+", ");
}
}
System.out.println();
}
}
Output:
Enter a name or 'Q' to quit: Tamaya
Enter a name or 'Q' to quit: Doug
Enter a name or 'Q' to quit: Lakshmi
Enter a name or 'Q' to quit: Q
The names you entered are: Tamaya, Doug, Lakshmi.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.