You should code to an interface. ArrayList
is the implementation. List is the interface.
You have an infinite loop. You need to decide on how to terminate the loop, otherwise code after the loop will not get executed.
In fact, when I copied your code to my Eclipse IDE, it flagged the following line of the code as Unreachable code
System.out.println("The Grocery List: " +shopList);
In the below code, I decided that simply hitting ENTER will terminate the loop.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ShopList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> shopList = new ArrayList<>();
while (true) {
System.out.print("Enter an item (or just hit 'ENTER' to quit): ");
String item = sc.nextLine();
if (item.isEmpty()) {
break;
}
else {
shopList.add(item);
}
}
System.out.println("The Grocery List: " +shopList);
sc.close();
}
}
Output from a sample run:
(Note that the second last entry was the TAB key and in the last entry, I hit the ENTER by itself which meant that item
was an empty string.)
Enter an item (or just hit 'ENTER' to quit): s
Enter an item (or just hit 'ENTER' to quit): %
Enter an item (or just hit 'ENTER' to quit): mvosp[5rt04j89w
Enter an item (or just hit 'ENTER' to quit): *&^$^&$ghdtr d df
Enter an item (or just hit 'ENTER' to quit):
Enter an item (or just hit 'ENTER' to quit):
The Grocery List: [s, %, mvosp[5rt04j89w, *&^$^&$ghdtr d df, ]