Issue
I have been trying to get the last name in this list in order to output it using list.size()
. However, list.size()
only prints the number of names in an array.
Is there a simpler way to explain how I can only record the last name (which is Anna in this case) and print it out when while loop is broken/stopped?
The following names are inputted by the user using scanner utility:
John
Marry
Anderson
Anna
Scanner scanner = new Scanner(System.in);
ArrayList<String> listOfNames = new ArrayList<>();
while (true) {
String input = scanner.nextLine();
if (input.equals("")) {
System.out.println(listOfNames.size());
break;
}
listOfNames.add(input);
}
Solution
From my understanding you want to print out the last item in the list.
If that is the case you can simply use the following code:
System.out.println(listOfNames.get(listOfNames.size() - 1));
Explanation:
.get()
- this method of Collections Framework (which List is part of) returns the element at a particular index. Thus, in the parenthesis, we need to specify the index of the last element in the List.
.size()
- this method of Collections Framework returns the number of elements in the List (in this case). The number we get is how many items is in the List.
Now, in most programming languages and situations indexes start at a 0. If we use the size of the list as the index of the last item, that won't work as the index will be out of bounds.
To use your example, you have 4 names in the List, hence .size() will return 4
.
Since the last index in the listOfNames List in your example is 3 (because items are indexed 0, 1, 2, 3 - that is all four elements), there is no item at index 4. So we would get a run-time error.
A very simple and common solution is to simply subtract 1 from the size.
Hopefully this helps. It might be confusing at first but you will get used to it as most of the time indexes start at 0.
Answered By - Vahe Aslanyan
Answer Checked By - Willingham (JavaFixing Volunteer)