Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Null pointer exception in inventory program

  1. #1
    Junior Member
    Join Date
    Dec 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Null pointer exception in inventory program

    import java.util.Arrays;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import java.util.Locale;
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
     
    class InventoryGUI extends JFrame {
     
    	private static final long serialVersionUID = 1L;
    //Navigate inventory
    	private static final int NAVIGATION_MODE = 0;
     
    //Add new Items
    	private static final int ADDITION_MODE = 1;
    //Change items
    	private static final int MODIFICATION_MODE = 2;
    //Stores status of application
    	private int currentMode;
            JTextField itemNumber = new JTextField();
    	JTextField ISBN = new JTextField();
    	JTextField title = new JTextField();
    	JTextField authorName = new JTextField();
    	JTextField year = new JTextField();
    	JTextField pubName = new JTextField();
    	JTextField price = new JTextField();
    	JTextField valueOfInventory = new JTextField();
     
    	JButton next = new JButton("Next >");
    	JButton previous = new JButton("< Previous");
     
    	JButton first = new JButton("<< First");
    	JButton last = new JButton("Last >>");
     
    	JButton add = new JButton("Add");
    	JButton delete = new JButton("Delete");
    	JButton modify = new JButton("Modify");
     
    //Save or apply changes
    	JButton saveOrApply = new JButton("Save");
     
    //Search or cancel changes
    	JButton searchOrCancel = new JButton("Search");
     
     
    	private Inventory inventory;
     
    //Current index
    	private int currentIndex = 0;
     
    	public InventoryGUI(Inventory inventory) {
    	//Create GUI
    		super();
    		this.inventory = inventory;
     
    		setTitle("Bookstore Part 6");
    		setBounds(0, 0, 860, 500);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		createGUI();
    		pack();
     
    		setLocationRelativeTo(null);
     
    		first.addActionListener(new ActionListener() {
     
    			public void actionPerformed(ActionEvent e) {
    				showFirst();
    			}
    		});
     
    		previous.addActionListener(new ActionListener() {
     
    			public void actionPerformed(ActionEvent e) {
    				showPrevious();
    			}
    		});
     
    		next.addActionListener(new ActionListener() {
     
    			public void actionPerformed(ActionEvent e) {
    				showNext();
    			}
    		});
     
    		last.addActionListener(new ActionListener() {
     
    			public void actionPerformed(ActionEvent e) {
    				showLast();
    			}
    		});
     
    		add.addActionListener(new ActionListener() {
     
    			public void actionPerformed(ActionEvent e) {
    				addItem();
    			}
    		});
     
    		delete.addActionListener(new ActionListener() {
     
    			public void actionPerformed(ActionEvent e) {
    				deleteItem();
    			}
    		});
     
    		modify.addActionListener(new ActionListener() {
     
    			public void actionPerformed(ActionEvent e) {
    				modifyItem();
    			}
    		});
     
    		saveOrApply.addActionListener(new ActionListener() {
     
    			public void actionPerformed(ActionEvent e) {
    				if (getCurrentMode() == NAVIGATION_MODE) {
    					saveInventory();
    				} else {
    					apply();
    				}
    			}
    		});
     
    		searchOrCancel.addActionListener(new ActionListener() {
     
    			public void actionPerformed(ActionEvent e) {
    				if (getCurrentMode() == NAVIGATION_MODE) {
    					searchInventory();
    				} else {
    					cancel();
    				}
    			}
    		});
     
    		updateGUI();
    	}
     
    //Prepares to add new item
    	protected void addItem() {
    		clearFields();
     
    		Integer newItemNumber = inventory.getMaxItemNumber() + 1;
    		itemNumber.setText(newItemNumber.toString());
     
    		title.requestFocus();
     
     
     
    		setCurrentMode(ADDITION_MODE);
    	}
     
    //Updates item
    	protected void apply() {
                 int newItem = Integer.valueOf(itemNumber.getText());
     
     
    		String newISBN = ISBN.getText();
    		String newTitle = title.getText();
    		String newauthorName = authorName.getText();
    		int newYear;
                    try {
                        newYear = Integer.parseInt(year.getText());
                    } catch (Exception e){
                        showErrorMessage("Invalid year");
                        year.requestFocus();
                        return;
                    }
    		String newpubName = pubName.getText();
     
    		double newPrice;
    		try {
    			newPrice = Double.parseDouble(price.getText());
    		} catch (Exception e) {
    			showErrorMessage("Invalid value for price.");
    			price.requestFocus();
    			return;
    		}
     
     
     
    		if (currentMode == ADDITION_MODE) {
     
    			Book uf = new Book (newItem, newISBN, newTitle, newauthorName,
    					newYear, newpubName, newPrice);
     
    			inventory.addItem(uf);
    			currentIndex = inventory.getItemCount() - 1;
     
    		} else if (currentMode == MODIFICATION_MODE) {
     
    			Book uf = inventory.getItem(currentIndex);
     
                            uf.setISBN(newISBN);
    			uf.setTitle(newTitle);
    			uf.setauthorName(newauthorName);
    			uf.setYear(newYear);
    			uf.setpubName(newpubName);
    			uf.setPrice(newPrice);
    		}
     
    		setCurrentMode(NAVIGATION_MODE);
    		updateGUI();
    	}
    //Sets GUI for navigation
    	protected void cancel() {
    		setCurrentMode(NAVIGATION_MODE);
    		updateGUI();
    	}
     
    	//Clears editable fields
    	private void clearFields() {
                    itemNumber.setText("");
    		ISBN.setText("");
    		title.setText("");
    		authorName.setText("");
    		year.setText("");
    		pubName.setText("");
    		price.setText("");
     
    	}
     
    //Creates GUI
    	private void createGUI() {
    		JPanel itemPanel = new JPanel(new GridLayout(0, 4, 5, 5));
                    itemPanel.add(new JLabel("Number of Items"));
                    itemPanel.add(itemNumber);
     
    		itemPanel.add(new JLabel("ISBN:"));
    		itemPanel.add(ISBN);
     
    		itemPanel.add(new JLabel("Title:"));
    		itemPanel.add(title);
     
    		itemPanel.add(new JLabel("Author: "));
    		itemPanel.add(authorName);
     
    		itemPanel.add(new JLabel("Year: "));
    		itemPanel.add(year);
     
    		itemPanel.add(new JLabel("Publisher: "));
    		itemPanel.add(pubName);
     
    		itemPanel.add(new JLabel("Price: $"));
    		itemPanel.add(price);
     
     
    		itemPanel.add(new JLabel("Value of Entire Inventory: $"));
    		itemPanel.add(valueOfInventory);
    		valueOfInventory.setEditable(false);
     
    		JPanel inventoryPanel = new JPanel(new BorderLayout(5, 5));
    		inventoryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
     
    		inventoryPanel.add(new LogoPanel(getWidth(), 80), BorderLayout.NORTH);
     
    		inventoryPanel.add(itemPanel, BorderLayout.CENTER);
     
    		JPanel bottomPanel = new JPanel(new GridLayout(2, 1, 5, 5));
     
    		JPanel navigationPanel = new JPanel(new GridLayout(1, 7, 5, 5));
    		navigationPanel.add(first);
    		navigationPanel.add(previous);
    		navigationPanel.add(add);
    		navigationPanel.add(delete);
    		navigationPanel.add(modify);
    		navigationPanel.add(next);
    		navigationPanel.add(last);
    		bottomPanel.add(navigationPanel);
     
    		JPanel extraPanel = new JPanel(new GridLayout(0, 2, 5, 5));
    		extraPanel.add(saveOrApply);
    		extraPanel.add(searchOrCancel);
    		bottomPanel.add(extraPanel);
     
    		inventoryPanel.add(bottomPanel, BorderLayout.SOUTH);
    		setContentPane(inventoryPanel);
     
    		setCurrentMode(NAVIGATION_MODE);
    	}
    //Deletes items
    	protected void deleteItem() {
    		if (isInventoryEmpty()) {
    			return;
    		}
    		if (JOptionPane.showConfirmDialog(this,
    				"Do you really want to delete this item?", "Confirmation",
    				JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
    			inventory.deleteItem(currentIndex);
    			currentIndex = inventory.getItemCount() - 1;
    			updateGUI();
    		}
    	}
     
    	public int getCurrentMode() {
    		return currentMode;
    	}
     
    //Checks if inventory is empty
    	private boolean isInventoryEmpty() {
    		if (inventory.getItemCount() == 0) {
    			JOptionPane.showMessageDialog(this, "The Inventory is Empty!");
    			return true;
    		}
    		return false;
    	}
     
    //Prepares for modifications
    	protected void modifyItem() {
    		if (isInventoryEmpty()) {
    			return;
    		}
    		setCurrentMode(MODIFICATION_MODE);
    	}
     
    //Saves inventory
    	protected void saveInventory() {
    		if (isInventoryEmpty()) {
    			return;
    		}
    		String[] items = inventory.serialize();
     
    		File file;
     
    		file = new File("c:\\data");
    		if (!file.exists()) {
    			file.mkdir();
    		}
     
    		file = new File("c:\\data\\inventory.dat");
    		if (file.exists()) {
    			file.delete();
    		}
     
    		try {
    			file.createNewFile();
    		} catch (IOException e) {
    			showErrorMessage("Failed to create the Inventory file.");
    			return;
    		}
     
    		try {
    			FileWriter fw = new FileWriter(file);
    			for (int i = 0; i < items.length; i++) {
    				fw.write(items[i] + "\n");
    			}
    			fw.close();
     
    			JOptionPane.showMessageDialog(this, "File successfully saved!");
    		} catch (IOException e) {
    			showErrorMessage("Failed to write the Inventory file.");
    		}
    	}
     
    	//Searches inventory
    	protected void searchInventory() {
    		if (isInventoryEmpty()) {
    			return;
    		}
    		String itemName = JOptionPane.showInputDialog(this,
    				"Enter the Item Name", "Search Item",
    				JOptionPane.QUESTION_MESSAGE);
     
    		if (itemName != null) {
    			int item = inventory.getItemByName(itemName);
    			if (item != -1) {
    				currentIndex = item;
    				updateGUI();
    			} else {
    				showErrorMessage(String.format("Item \"%s\" not found.",
    						itemName));
    			}
    		}
    	}
     
    	//Changes status of app
    	public void setCurrentMode(int currentMode) {
    		this.currentMode = currentMode;
     
    		switch (currentMode) {
     
    		case ADDITION_MODE:
    		case MODIFICATION_MODE:
    			first.setEnabled(false);
    			previous.setEnabled(false);
    			add.setEnabled(false);
    			modify.setEnabled(false);
    			delete.setEnabled(false);
    			next.setEnabled(false);
    			last.setEnabled(false);
    			saveOrApply.setText("Apply");
    			searchOrCancel.setText("Cancel");
    			setFieldsEditable(true);
    			break;
     
    		case NAVIGATION_MODE:
    			first.setEnabled(true);
    			previous.setEnabled(true);
    			add.setEnabled(true);
    			modify.setEnabled(true);
    			delete.setEnabled(true);
    			next.setEnabled(true);
    			last.setEnabled(true);
    			saveOrApply.setText("Save");
    			searchOrCancel.setText("Search");
    			setFieldsEditable(false);
    			break;
    		}
    	}
    //Sets fields editable
    	protected void setFieldsEditable(boolean editable) {
    		ISBN.setEditable(editable);
    		title.setEditable(editable);
    		authorName.setEditable(editable);
    		year.setEditable(editable);
    		pubName.setEditable(editable);
    		price.setEditable(editable);
    	}
     
    //Shows error
    	private void showErrorMessage(String message) {
    		JOptionPane.showMessageDialog(this, message, "Error",
    				JOptionPane.ERROR_MESSAGE);
    	}
    //Displays first item
    	protected void showFirst() {
    		if (isInventoryEmpty()) {
    			return;
    		}
    		currentIndex = 0;
    		updateGUI();
    	}
     
    //displays last
    	protected void showLast() {
    		if (isInventoryEmpty()) {
    			return;
    		}
    		currentIndex = inventory.getItemCount() - 1;
    		updateGUI();
    	}
     
    //Displays next
    	private void showNext() {
    		if (isInventoryEmpty()) {
    			return;
    		}
    		if (currentIndex < inventory.getItemCount() - 1) {
    			currentIndex++;
    			updateGUI();
    		} else {
    			showFirst();
    		}
    	}
     
    //Shows previous
    	private void showPrevious() {
    		if (isInventoryEmpty()) {
    			return;
    		}
    		if (currentIndex > 0) {
    			currentIndex--;
    			updateGUI();
    		} else {
    			showLast();
    		}
    	}
     
    //Updates fields
    	public void updateGUI() {
    		if (currentIndex != -1) {
    			Book  item = inventory.getItem(currentIndex);
     
    			ISBN.setText(String.valueOf(item.getISBN()));
    			title.setText(item.getTitle());
    			authorName.setText(String.valueOf(item.getauthorName()));
    			year.setText(String.format("%d", item.getYear()));
    			pubName.setText(String.format( item.getpubName()));
    			price.setText(String.format("%.2f", item.getPrice()));
     
    		} else {
    			clearFields();
    		}
     
    		valueOfInventory.setText(String.format("%.2f", inventory.getValueOfInventory()));
    	}
    }
    public class Bookstore6{
     
    	public static void main(String args[]) {
     
    		Book  p1 = new Book  (1,"AIF435", "Java Programming", "Bob Oracle", 2012, "Sue Oracle", 8.74);
    		Book  p2 = new Book (1,"ABR43F", "Cats 101", "Walter White", 2011, "Skyler White", 9.46);
    		Book  p3 = new Book  (1,"AIF435", "Dogs 201", "Jesse Pinkman", 2004, "Bob Joe", 10.00);
    		Book  p4 = new Book (1,"YUI46", "Adventure Books", "Laurie Smith", 2011, "Joe Smith", 8.97);
    		Book  p5 = new Book  (1,"AGVI345", "Candy Corn", "Jimmy Johnson", 2010, "Sue Zumba", 5.55);
    		Book  p6 = new Book  (1,"UIFE45", "Childrens Books", "Brittany Anderson", 2012, "Alex Moona", 12.75);
     
     
    		Inventory inv = new Inventory();
    		inv.addItem(p1);
    		inv.addItem(p2);
    		inv.addItem(p3);
    		inv.addItem(p4);
    		inv.addItem(p5);
    		inv.addItem(p6);
    		inv.sortItems();
     
    		new InventoryGUI(inv).setVisible(true);
    	}
    }
     class LogoPanel extends JPanel {
     
    	private static final long serialVersionUID = 1L;
     
    	public LogoPanel(int width, int height) {
    		super();
    		setPreferredSize(new Dimension(width, height));
    	}
     
     
    	public void paint(Graphics g) {
    		g.setColor(Color.BLACK);
    		g.fill3DRect(0, 0, getWidth(), getHeight(), true);
     
    		int midX = getWidth() / 2;
    		int midY = getHeight() / 2;
     
    		g.setColor(Color.RED);
    		g.fillOval(midX - 100, midY - 25, 50, 50);
     
    		g.setColor(Color.WHITE);
    		g.setFont(new Font("Verdana", Font.BOLD, 28));
    		g.drawString("Lauren's Logo", midX - 70, midY + 10);
    	}
     
    }
     
    class Book {
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
    private int itemNumber;
    private String ISBN;
    private String title;
    private String authorName;
    private int year;
    private String pubName;
    private double price;
     
    public Book ( int itemNumber, String ISBN, String title, String authorName, int year, String pubName, double price)
    {
    this.itemNumber = itemNumber;
    this.ISBN = ISBN;
    this.title = title;
    this.authorName = authorName;
    this.year = year;
    this.pubName = pubName;
    this.price = price;
     
    }
     
    public int getItemNumber() {
        return itemNumber;
     }
    public void setItemNumber() {
        this.itemNumber = itemNumber;
    }
    public String getISBN() {
    	return ISBN;
    }
    public void setISBN (String identNum){
    	this.ISBN = ISBN;
    }
    public String getTitle () {
    	return title;
    }
    public void setTitle (String title) {
    	this.title = title;
    }
    public String getauthorName () {
    	return authorName;
    }
    public void setauthorName (String authorName) {
    	this.authorName = authorName;
    }
    public String getpubName () {
    	return pubName;
    }
    public void setpubName (String pubName) {
    	this.pubName = pubName;
    }
    public int getYear () {
    	return year;
    }
    public void setYear (int year) {
    	this.year = year;
    }
    public double getPrice () {
    	return price;
    }
     
    public  void setPrice (double bookPrice){
    	this.price = price;
    }
    	public String serialize() {
    		return String.format("%d|%s|%s|%s|%d|%s|%.2f",itemNumber, ISBN, title, authorName,
    				year, pubName,price);
    	}
     
    }
     
     
     
    class Inventory {
    	private Book[] bookList;
    	private int itemCount = 0;
     
    	public Inventory() {
    		bookList = new Book[100];
    	}
            	public void add(Book p) {
    		Book[] temp = new Book[bookList.length+1];
    		for (int i = 0; i < bookList.length; i++) {
    			temp[i] = bookList[i];
    		}
    		temp[temp.length-1] = p; // add it at the end
    		bookList = temp;
    		itemCount++;
    	}
     
    	public void addItem(Book p) {
    		bookList[itemCount++] = p;
    	}
     
    	public void deleteItem(int currentIndex) {
    		for (int i = currentIndex; i < (getItemCount() - 1); i++) {
    			bookList[i] = bookList[i + 1];
    		}
    		bookList[getItemCount() - 1] = null;
    		itemCount--;
    	}
     
    	public Book getItem(int i) {
    		return bookList[i];
    	}
     
    	public int getItemByName(String title) {
    		int item = -1;
    		if (itemCount > 0) {
    			for (int i = 0; i < itemCount; i++) {
    				Book uf = bookList[i];
    				if (title.equalsIgnoreCase(uf.getTitle())) {
    					item = i;
    					break;
    				}
    			}
    		}
    		return item;
    	}
     
    	public int getItemCount() {
    		return itemCount;
    	}
     
    public double getValueOfInventory (){
    		double total = 0;
    	for (int i = 0; i < bookList.length; i++){
     
    			total += bookList[i].getPrice();
    		}
     
    		return total;
    	}
     
    	public int getMaxItemNumber() {
    		int max = 0;
    		if (itemCount > 0) {
    			for (int i = 0; i < itemCount; i++) {
    				Book uf = bookList[i];
    				if (uf.getItemNumber() > max) {
    					max = uf.getItemNumber();
    				}
    			}
    		}
    		return max;
    	}
     
     
    	public void sortItems() {
     
    		int n = getItemCount();
    		for (int search = 1; search < n; search++) {
    			for (int i = 0; i < n - search; i++) {
    				if (bookList[i].getTitle().compareToIgnoreCase(
    						bookList[i + 1].getTitle()) > 0) {
     
    					Book temp = bookList[i];
    					bookList[i] = bookList[i + 1];
    					bookList[i + 1] = temp;
    				}
    			}
    		}
    	}
     
    	public String[] serialize() {
    		String[] items = new String[getItemCount()];
    		for (int i = 0; i < itemCount; i++) {
    			items[i] = getItem(i).serialize();
    		}
    		return items;
    	}
    }

    Exception in thread "main" java.lang.NullPointerException
    at bookstoreprogrampart5.Inventory.getValueOfInventor y(BookstoreProgramPart5.java:675)
    at bookstoreprogrampart5.InventoryGUI.updateGUI(Books toreProgramPart5.java:492)
    at bookstoreprogrampart5.InventoryGUI.<init>(Bookstor eProgramPart5.java:143)
    at bookstoreprogrampart5.BookstoreProgramPart5.main(B ookstoreProgramPart5.java:516)

    Not too sure why I can't solve this. Ive been sick for weeks, so I'm sure that has something to do with it. Any suggestions would be greatly appreciated.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,434
    Thanks
    49
    Thanked 2,216 Times in 2,189 Posts

    Default Re: Null pointer exception in inventory program

    xception in thread "main" java.lang.NullPointerException
    at bookstoreprogrampart5.Inventory.getValueOfInventor y(BookstoreProgramPart5.java:675)
    There is a variable with a null value when line 675 is executed. Look at that line, find the variable with the null value and then backtrack in the code to see why that variable does not have a valid value.
    If you can't see which variable is null, add a println statement just before line 675 that prints out the value of all the variables used on line 675.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Help With Null Pointer Exception
    By kendraheartt in forum What's Wrong With My Code?
    Replies: 17
    Last Post: August 15th, 2012, 10:41 PM
  2. Help With Null Pointer Exception
    By kendraheartt in forum Exceptions
    Replies: 1
    Last Post: August 15th, 2012, 10:36 PM
  3. [SOLVED] Null Pointer Exception
    By wltrallen2 in forum Object Oriented Programming
    Replies: 7
    Last Post: May 27th, 2012, 10:21 AM
  4. Null Pointer Exception Help !!
    By AlterEgo1234 in forum Member Introductions
    Replies: 1
    Last Post: March 27th, 2011, 10:07 AM
  5. [SOLVED] Null Pointer Exception
    By musasabi in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 11th, 2010, 09:25 PM