make sure it works 1 Write a Java program that allows a user
make sure it works
1. Write a Java program that allows a user to input words at the command line. Your program should stop accepting words when the user enters \"STOP\". Store the words in an ArrayList. The word STOP should not be stored in the list.
Next, print the size of the list, followed by the contents of the list.
Then, remove the first and last words stored in the list, but only if the list has a length greater than two. Finally, reprint the contents of the list.
Sample Run:
Note: For this activity, you must use the class name, Main and the method, main.
Solution
Main.java
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(\"Please enter words, enter STOP to stop the loop: \");
String s = \"\";
ArrayList<String> list = new ArrayList<String>();
s = scan.next();
while(!s.equalsIgnoreCase(\"STOP\")){
list.add(s);
s = scan.next();
}
System.out.println();
System.out.println(list.size());
System.out.println(list);
if(list.size()>2){
list.remove(0);
list.remove(list.size()-1);
System.out.println(list);
}
}
}
Output:
Please enter words, enter STOP to stop the loop:
cup
spoon
fork
bowl
plate
knife
STOP
6
[cup, spoon, fork, bowl, plate, knife]
[spoon, fork, bowl, plate]
