title: Java Objects Array: How to print only first elements of objects?
body: <p>I'm trying to create a program that takes book names, number of pages, and publishing year as user input. When user does not input anything to name field, program should ask user what will be printed: only names of the books or all information given by user. Here is my main code:</p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.Scanner;
  
  public class Main {
  
      public static void main(String[] args) {
          int index = 0;
          Scanner reader = new Scanner(System.in);
          ArrayList&lt;Books&gt; book = new ArrayList&lt;&gt;();
          while (true) {
              System.out.println("Name of the book: ");
              String name = reader.nextLine();
              if (name.isEmpty()) {
                  break;
              }
              System.out.println("Number of pages: ");
              int pages = Integer.parseInt(reader.nextLine());
              System.out.println("Year: ");
              int year = Integer.parseInt(reader.nextLine());
              book.add(new Books(name,pages,year));
          }
          while (true) {
              System.out.println("What do you want to print?");
              String whatwillbeprinted = reader.nextLine();
              if (whatwillbeprinted.equals("everything")) {
                  while(index &lt; book.size()) {
                      System.out.println(book.get(index));
                      index++;
                  }
              }
              if (whatwillbeprinted.equals("names")) {
                  while(index &lt; book.size()) {
                      // print only names of the books
                  }
              }
          }
          }
      }
  </code></pre>
  
  <p>And here is my Java class named Books:</p>
  
  <pre><code>public class Books {
      private String name;
      private int pages;
      private int year;
  
      public Books(String name, int pages, int year) {
          this.name = name;
          this.pages = pages;
          this.year = year;
      }
      @Override
      public String toString() {
          return this.name + ", " + this.pages + ", " + this.year;
      }
  }
  </code></pre>
  
  <p>Everything operates correctly until that last while-statement. How can I print only first elements of my objects (names of the books)? Thanks in advance.</p>