0

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);
        }
Steffen
  • 501
  • 1
  • 14
belinyom
  • 31
  • 6
  • Does [this](https://stackoverflow.com/a/687842/19926805) help you? – Steffen Sep 08 '22 at 18:08
  • Thank you very much, it did help. However, I did not understand the logic and reason behind .size starts with the value 1 and .get starts with the value 0 index in an array. Is it because that the 0 cannot be sized compared to 1 and 0 can be counted instead of sized? – belinyom Sep 08 '22 at 19:02
  • In nearly every programming language, the 1st item of an array has the index 0. That's just a Language Specification. The `.size()` method doesn't start with a 1. You could have an empty array, therefor the size would be 0. – Steffen Sep 08 '22 at 19:36

1 Answers1

0

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.

Vahe Aslanyan
  • 76
  • 1
  • 4