/* * T01n22.java -- A demonstration of an array of objects. Here, we want to * have an array of books. * * We've created a Book class that has only three data members and * the default constructor; no methods are defined. This is unusual; * normally, you'd write a complete class with getters, setters, etc. * I'm doing this to show that you can use classes to create a simple * collection of data items that belong together. (In other languages, * such collections of data items are called structures or records.) * Remember, this use of a class is NOT the norm! * * An I/O Note: In this program we have to mix integer and string input. * Scanner's nextInt() will stop reading when it finds a character that * can't be used in a number, such as the newline (\n) character that you * have to type to end your input. That will be read by the next * input method. If that next input happens to be nextLine(), then * it sees \n first, and assumes that's all the input it's meant to accept. * To work around this behavior, this program reads everything as a string, * and converts to integers what were entered as integers. Of course, * a more complete program would verify that the input is actually a * legal integer first, as we've seen in earlier examples. */ import java.util.*; class Book { public String title; // The title of the book public String author; // The name of the book's author public int copyright; // The date the work was published (approx.) } public class T01n22 { public static void main (String [] args) { Book[] volumes; // our array of book objects char answer; // Y/N response from the user int quantity = 0, // current number of books entered by the user limit = 0; // user-specified quantity of books to be entered Scanner keyboard = new Scanner (System.in); // source of user input System.out.print("How many books will you enter? : "); limit = Integer.parseInt(keyboard.nextLine()); volumes = new Book[limit]; while (quantity < limit) { volumes[quantity] = new Book(); System.out.print("\nEnter book " + (quantity+1) + "'s title : "); volumes[quantity].title = keyboard.nextLine(); System.out.print("Enter \"" + volumes[quantity].title + "\"'s author : "); volumes[quantity].author = keyboard.nextLine(); System.out.print("Enter \"" + volumes[quantity].title + "\"'s copyright date : "); volumes[quantity].copyright = Integer.parseInt(keyboard.nextLine()); quantity++; } if (quantity > 0) { System.out.println("\nHere are the volumes in your collection:"); for (int i = 0; i < quantity; i++) System.out.println("\"" + volumes[i].title + "\", by " + volumes[i].author + " (" + volumes[i].copyright + ")"); System.out.println(); } } }