package Books;
import java.util.*;
class Book{
private int isbn;
private String title;
private static int count=0;
public Book(){
count ++;
}
public void readBook(){
int isbn=0;
Scanner input = new Scanner(System.in);
String temp;
Book book = new Book();
System.out.print("ISBN: ");
temp=input.nextLine();
book.setIsbn(Integer.parseInt(temp));
System.out.print("title: ");
String title = input.nextLine();
book.setTitle(title);
}
public int getCount(){
return count;
}
public void incrCount(){
this.count++;
}
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
And the main one :
package Books;
import java.io.IOException;
import java.util.Scanner;
/**
*
* @author Ionut
*/
public class Books {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, NumberFormatException{
Scanner input = new Scanner(System.in);
Book book = new Book();
int choice;
Book[] books = new Book[10];
int currentIndex;
String temp;
for (int i = 0; i < books.length; i++) {
books[i] = new Book();
}
while(true){
do{
System.out.println("Library System");
System.out.println(" 1. add book");
System.out.println(" 2. display books");
System.out.println(" 3. save to file");
System.out.println(" 4. load from file");
System.out.println(" 0. exit");
System.out.print("choice: ");
temp = input.nextLine();
choice = Integer.parseInt(temp);
}while ((choice < 0) || (choice > 4));
switch (choice){
case 1: //read isbn, title
currentIndex=book.getCount();
book.readBook();
//add current book to the array
books[currentIndex+1] = book;
book.incrCount();
break;
case 2: //display array of books
currentIndex=book.getCount();
System.out.println("ISBN Title ");
for(int i=0; i< currentIndex; i++){
System.out.println(books[i].getIsbn()+" "+books[i].getTitle()+" ");
}
break;
case 3: break;
case 4: break;
case 0: return ;
}
}//end while true
}
}
In the main one I've introduced `
for (int i = 0; i < books.length; i++) {
books[i] = new Book();
}
` And now I no longer get the NullPointerException error but I get ArrayIndexOutOfBoundsException.
run:
Library System
1. add book
2. display books
3. save to file
4. load from file
0. exit
choice: 1
ISBN: 1
title: 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
at Books.Books.main(Books.java:49)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)
Any help is well apreciated. I dont understand why i get this error, I just initialized the array why would it go out of bounds ?