Member Avatar for buchanan23

OK, so here is my problem. I have created this application that inventory's books & magazines. Everything compiles fine. I prompt the user at the beginning to pick the length of the array (stored in numBooks) then when it comes time to pass the array to the GUI, I get an error that says

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at TestBooks.main(TestBooks.java:193)

My problem, I guess, is that I am not passing the entire array correctly to the GUI. Now, there is an entirely different issue of me needing to get my buttons to work, but I think I just want help right now with how to properly pass the array in to the GUI. Any help you could give would be great, and just so you know, I am not an expert here (obviously) so let's try to keep it simple if we can. Thanks so much!

Oh and one more thing... if there are some better ways to do what I have already done, I would appreciate that too.


First file titled TestBooks.java

//Inventory Program Part 4
//This Program keeps and inventory of books and magazines
//Brandon Buchanan

import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.text.*;
import java.awt.event.*;
import java.applet.*;


public class TestBooks extends JFrame// define class
{

	public static JButton firstButton;
	public static JButton prevButton;
	public static JButton nextButton;
	public static JButton lastButton;
	DecimalFormat decimal = new DecimalFormat("$0.00");

  	public TestBooks(Books book)
  	{
    		super("Inventory GUI");

      		Container con = getContentPane();

		BoxLayout layout = new BoxLayout(con, BoxLayout.Y_AXIS);
		con.setLayout(layout);

		JPanel topPanel= new JPanel();
		JPanel bottomPanel= new JPanel();
		con.add(topPanel, BorderLayout.NORTH);
		con.add(bottomPanel, BorderLayout.SOUTH);

    		if (book instanceof Magazine)
    		{ 

			JLabel label1 = new JLabel( "Title: " + book.getBookTitle() );
    			add( label1 );
      			JLabel issueLabel = new JLabel( "Issue: " + ((Magazine)book).getMagazineIssue() );
			add( issueLabel );
			JLabel label2 = new JLabel( "Price: " + (decimal.format(((Magazine)book).getBookPrice())) );
    			add( label2 );
			JLabel label3 = new JLabel( "Quantity in stock: " + book.getBookQuantity() );
    			add( label3 );
			JLabel label4 = new JLabel( "Magazine Total: " + (decimal.format(((Magazine)book).getBookInventory())) );
    			add( label4 );
			JLabel restockLabel = new JLabel( "Magazine Total with restocking fee: " + (decimal.format(((Magazine)book).getMagazineValue())) );
			add( restockLabel );

			topPanel.add(label1);
			topPanel.add(issueLabel);
			topPanel.add(label2);
			topPanel.add(label3);
			topPanel.add(label4);
			topPanel.add(restockLabel);

    		}
    		else
    		{

			JLabel label1 = new JLabel( "Title: " + book.getBookTitle() );
    			add( label1 );
      			JLabel isbnLabel = new JLabel( "ISBN: " + ((Books)book).getBookIsbn() );
			add( isbnLabel );
			JLabel label2 = new JLabel( "Price: " + (decimal.format(book.getBookPrice())) );
    			add( label2 );
			JLabel label3 = new JLabel( "Quantity in stock: " + book.getBookQuantity() );
    			add( label3 );
			JLabel label4 = new JLabel( "Book Total: " + (decimal.format(book.getBookInventory())) );
    			add( label4 );

			topPanel.add(label1);
			topPanel.add(isbnLabel);
			topPanel.add(label2);
			topPanel.add(label3);
			topPanel.add(label4);

    		}
		
		firstButton = new JButton("|<<");
		prevButton = new JButton("<<");
		nextButton = new JButton(">>");
		lastButton = new JButton(">>|");
		bottomPanel.add(firstButton);
		bottomPanel.add(prevButton);
		bottomPanel.add(nextButton);
		bottomPanel.add(lastButton);	

    		pack();        
    		setVisible( true);
  	}
  
  	// main method begins execution of Java application
  	public static void main( String args[] )
  	{
   		 // This explains the program
    		System.out.println( "\nThis program will provide an inventory of books and/or magazines." );

    		// create Scanner to obtain input from command window
    		Scanner input = new Scanner( System.in ); 

    		// Prompt user for number of books to enter
    		System.out.println( "\nHow many items would you like to inventory today?" );
    		int numBooks = input.nextInt(); // Reads the data entered

    		// Create an array of Book objects according to the number that the user inputs above       
    		Books[] bookArray = new Books[numBooks];

    		// set the total inventory value
    		double bookTotal = 0.00;

    		// Begin for loop & declare variable i to store array items in until total number of books has been met
    		for (int i = 0; i < numBooks; i++)
    		{
      			// create book objects within for loop so array is not overwritten on each itteration
      			Books book = new Books();

      			// create magazine objects within for loop so array is not overwritten on each itteration
      			Magazine mag = new Magazine();

      			// create another Scanner to obtain input from command window during for loop
      			Scanner in = new Scanner( System.in );    

      			// prompt for book or magazine
      			System.out.println( "\nIs this item a book or magazine? (Enter 1 for Book and 2 for Magazine.)" );
      			int type = input.nextInt(); //

      			if (type == 1)
      			{
        			// Request the book title
        			System.out.println( "\nPlease enter book title: " );
        			book.setBookTitle(in.nextLine()); // Reads the data entered

        			// Request the isbn for the book
        			System.out.println( "\nPlease enter the ISBN for \"" + book.getBookTitle() + "\"" );
        			book.setBookIsbn(in.nextInt()); // Reads the data entered

        			// Request the price of the book
        			System.out.println( "\nPlease enter the dollar amount for \"" + book.getBookTitle() + "\"" );
        			book.setBookPrice(in.nextDouble()); // Reads the data entered

        			//Request the number of books in stock
        			System.out.println( "\nPlease enter the number of books currently in stock:" );
        			book.setBookQuantity(in.nextInt()); // Reads the data entered
        			System.out.println( "\nBook information entered successfully!" ); 
     

        			// marks the completion of 1 itteration of for loop
        			bookArray[i] = book;



      			}
      			else
     	 		{
        			// Request the magazine title
        			System.out.println( "\nPlease enter magazine title:" );
        			mag.setBookTitle(in.nextLine()); // Reads the data entered

        			// Request the isbn for the magazine
        			System.out.println( "\nPlease enter the Issue Number for \"" + mag.getBookTitle() + "\"" );
        			mag.setMagazineIssue(in.nextLine()); // Reads the data entered

        			// Request the price of the magazine
        			System.out.println( "\nPlease enter the dollar amount for \"" + mag.getBookTitle() + "\"" );
        			mag.setBookPrice(in.nextDouble()); // Reads the data entered

        			//Request the number of magazines in stock
        			System.out.println( "\nPlease enter the number of magazines currently in stock:" );
        			mag.setBookQuantity(in.nextInt()); // Reads the data entered
        			System.out.println( "\nMagazine information entered successfully!" );      

        			// marks the completion of 1 itteration of for loop
        			bookArray[i] = mag;


      			} // end if

    		} // end for loop that populates the array

    		TestBooks myFrame = new TestBooks(bookArray[numBooks]);
		myFrame.setSize( 400, 300 );
		myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );


  }// end method main

}// end class TestBooks

next file is called Books.java

//Checkpoint: Inventory Program Part 1
//This program will provide an inventory of books
//Brandon Buchanan



public class Books // define class
{
	private String bookTitle;
	private int bookIsbn;
	private double bookPrice;
	private int bookQuantity;

	//This constructor takes no arguments
	public Books(){

      	}   

      	//This constructor takes title, isbn, price, and quantity as arguments
     	public Books(String title, int isbn, double price, int quantity )
	{
		this.bookTitle=title;
		this.bookIsbn=isbn;
		this.bookPrice=price;
		this.bookQuantity=quantity;
	}

	public void setBookTitle(String title)
	{
		bookTitle = title;
	}

	public String getBookTitle()
	{
		return bookTitle;
	}

	public void setBookIsbn(int isbn)
	{
		bookIsbn=isbn;
	}

	public int getBookIsbn()
	{
		return bookIsbn;
	}

	public void setBookPrice(double price)
	{
		bookPrice=price;
	}

	public double getBookPrice()
	{
		return bookPrice;
	}

	public void setBookQuantity(int quantity)
	{
		bookQuantity=quantity;
	}

	public int getBookQuantity()
	{
		return bookQuantity;
	}

	public double getBookInventory()
	{
		return bookPrice * bookQuantity;
	}
}

and the last file is called Magazine.java

//Checkpoint: Inventory Program Part 3
//This is a subclass of the class Books
//Brandon Buchanan


public class Magazine extends Books // define class
{
	
	private String magazineIssue;

	// This constructor takes no arguments
	public Magazine(){
	
	}
	
	// this constructor pulls from class Books and adds book genre
	public Magazine(String title, int isbn, double price, int quantity, String issue )
	{
		super(title, isbn, price, quantity);
		this.magazineIssue=issue;
	}

	//
	public void setMagazineIssue(String issue)
	{
		magazineIssue = issue;
	}

	//
	public String getMagazineIssue()
	{
		return magazineIssue;
	}

	public double getMagazineValue()
	{
		return getBookInventory() * 1.05;
	}

}

Again, thanks so much for any help you can give!

Recommended Answers

All 14 Replies

TestBooks myFrame = new TestBooks(bookArray[numBooks]);

So if numBooks is (say) 2, you populate elements [0] and [1] in the array, but you pass element [2] to the GUI

Member Avatar for buchanan23

TestBooks myFrame = new TestBooks(bookArray[numBooks]);

So if numBooks is (say) 2, you populate elements [0] and [1] in the array, but you pass element [2] to the GUI

Will that pass both elements of my Array to the GUI. Using your example, I actually need to pass both elements to the array and then will need to use the first, next, previous, & last buttons that I am setting up next.

Does that make sense?

Using "array[number]" you're refer to 1 single element in array , which has a position number-1 (since the array indexes are starting from 0).
If you need to pass whole array - pass just the bookArray .

Yup, if you want the whole array, pass the whole array.

Using "array[number]" you're refer to 1 single element in array , which has a position number-1 (since the array indexes are starting from 0).

I think this is a typo. Element [n] is in position n+1, not n-1.
ie Element [0] is in the first position, [1] is in the second position etc

commented: oh .. yeah .. thanks .. my bad :$ +2
Member Avatar for buchanan23

Using "array[number]" you're refer to 1 single element in array , which has a position number-1 (since the array indexes are starting from 0).
If you need to pass whole array - pass just the bookArray .

Yup, if you want the whole array, pass the whole array.

So if I change my line to say:

TestBooks myFrame = new TestBooks(bookArray);

I get this error:

TestBooks.java:183: cannot find symbol
symbol : constructor TestBooks(Books[])
location: class TestBooks
TestBooks myFrame = new TestBooks(bookArray);

That's right. Your constructor takes a single Book as its parameter. If you want to pass an array of Book objects, the constructor's parameter needs to changed to an array.
It's confusing to call the class Books instead of Book - each instance represents a single Book, not some number of Books, and this obscures when you need a Book and when you need an array of Book objects.

Member Avatar for buchanan23

That's right. Your constructor takes a single Book as its parameter. If you want to pass an array of Book objects, the constructor's parameter needs to changed to an array.
It's confusing to call the class Books instead of Book - each instance represents a single Book, not some number of Books, and this obscures when you need a Book and when you need an array of Book objects.

Do you have any suggestions that might shoot me off in the right direction then to get this to work correctly?

Also, on another note, I am thinking that I will need to have my buttons functioning in order to verify if I have passed the whole array or not? Is that right?

Thanks!

Change the consrtuctor to
public TestBooks(Books[] arrayOfBooks)
, then decide which Book to display first, eg
Books book = arrayOfBooks[0];

You don't need the buttons to check that you have passed the right data - just send it to System.out and look at it!

Member Avatar for buchanan23

Change the consrtuctor to
public TestBooks(Books[] arrayOfBooks)
, then decide which Book to display first, eg
Books book = arrayOfBooks[0];

You don't need the buttons to check that you have passed the right data - just send it to System.out and look at it!

Great! I updated to what you said, and was able to get it to compile but am now confused where i put the System.out in order to check and see if the whole array has passed... again, sorry for my noobiness here, I am still learning.

Thanks.

Some debugging/testing hints:

For your Books class (please change that to Book!), add a
public String toString()
method that returns a string representation of the Book - maybe something easy like
return title + " " + isbn + " " + price ... etc.

Now you can see what's in your data by simply saying
System.out.println(book);
or
for (Book b : arrayOfBooks) {
System.out.println(b);
}

You can stick these statements anywhere you want to check that the data you have is what you expected (eg in the constructor, or after entering or editing a Book in the GUI). Start off with these in, then comment them out when it seems to be OK. If it subsequently goes wrong again, just un-comment them to find out why.

Member Avatar for buchanan23

Some debugging/testing hints:

For your Books class (please change that to Book!), add a
public String toString()
method that returns a string representation of the Book - maybe something easy like
return title + " " + isbn + " " + price ... etc.

Now you can see what's in your data by simply saying
System.out.println(book);
or
for (Book b : arrayOfBooks) {
System.out.println(b);
}

You can stick these statements anywhere you want to check that the data you have is what you expected (eg in the constructor, or after entering or editing a Book in the GUI). Start off with these in, then comment them out when it seems to be OK. If it subsequently goes wrong again, just un-comment them to find out why.

AWESOME!!! This was such a huge help! I think I can see now that all of the data is passing to the GUI... now if I can figure out how to make my buttons work??? I am going to work on that for a bit and see what happens. If I get stuck, I should start a new post that has to do with the buttons right? (This is my first post)

That's right. In your GUI you'll need the array, plus a variable that holds the number of the array element that you're currently working with. Your buttons just increment/decrement that number, then display the corresponding array element. You'll sort it out with a little thought.
And, yes, time to mark this solved and start a new topic if necessary.
Good luck
J

Member Avatar for buchanan23

That's right. In your GUI you'll need the array, plus a variable that holds the number of the array element that you're currently working with. Your buttons just increment/decrement that number, then display the corresponding array element. You'll sort it out with a little thought.
And, yes, time to mark this solved and start a new topic if necessary.
Good luck
J

Well, like I said, thanks again! I am so glad I found this site and so grateful for the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.