NullPointerException error
I am fairly new to java I have been working like mad at revamping this code and I feel like I am finally close to a good set up but I am getting this NullPointerException when I try to compile and execute. Any help would really be appreciated as I am stumped maybe my brain is just fried out on this at the moment I dont know.
I hope I posted this all right. The compiler is throwing back there error and it looks like this..........
Exception in thread "main" java.lang.NullPointerException
at Inventory.sortItems(Inventory6.java: 187)
at Inventory6.main(Inventory6.java:21)
Code Java:
public class Inventory6 {
public static void main(String[] args) {
DigitalFeature p1 = new DigitalFeature(1, "Nikon", 24, 65.99,
0.0);
DigitalFeature p2 = new DigitalFeature(2, "Panasonic", 16, 54.00,
0.0);
DigitalFeature p3 = new DigitalFeature(3, "Sony", 20, 75.00,
0.0);
Inventory inv = new Inventory();
inv.addItem(p1);
inv.addItem(p2);
inv.addItem(p3);
inv.sortItems();
new InventoryGUI(inv).setVisible(true);
}
}
class Camera {
protected int itemNumber;
protected static String name;
protected int unitsInStock;
protected double unitPrice;
public Camera(int item, String name, int units, double price) {
this.itemNumber = item;
this.name = name;
this.unitsInStock = units;
this.unitPrice = price;
}
public int getItemNumber() {
return itemNumber;
}
public String getName() {
return name;
}
public double getUnitPrice() {
return unitPrice;
}
public int getUnitsInStock() {
return unitsInStock;
}
public double getValueOfInventory() {
return unitsInStock * unitPrice;
}
public void setItemNumber(int itemNumber) {
this.itemNumber = itemNumber;
}
public void setName(String name) {
this.name = name;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setUnitsInStock(int unitsInStock) {
this.unitsInStock = unitsInStock;
}
public String serialize() {
return String.format("%d|%s|%d|%.2f", itemNumber, name, unitsInStock,
unitPrice);
}
}
class DigitalFeature extends Camera {
private double imageRes = 0.00;
public DigitalFeature(int item, String newName, int units, double price,
double string) {
super(item, name, units, price);
this.imageRes = string;
}
public double getimageRes() {
return imageRes;
}
public double getRestockingFee() {
return 0.05 * getUnitsInStock() * getUnitPrice();
}
public double getValueOfInventory() {
return 1.05 * getUnitsInStock() * getUnitPrice();
}
public void setImageRes(double imageRes) {
this.imageRes = imageRes;
}
@Override
public String serialize() {
return super.serialize() + String.format("|%s", imageRes);
}
}
class Inventory {
private DigitalFeature[] cameraList;
private int itemCount = 0;
public Inventory() {
cameraList = new DigitalFeature[3];
}
public void addItem(DigitalFeature p) {
cameraList[itemCount++] = p;
}
public void deleteItem(int currentIndex) {
for (int i = currentIndex; i < (getItemCount() - 1); i++) {
cameraList[i] = cameraList[i + 1];
}
cameraList[getItemCount() - 1] = null;
itemCount--;
}
public DigitalFeature getItem(int i) {
return cameraList[i];
}
public int getItemByName(String itemName) {
int item = -1;
if (itemCount > 0) {
for (int i = 0; i < itemCount; i++) {
DigitalFeature df = cameraList[i];
if (itemName.equalsIgnoreCase(df.getName())) {
item = i;
break;
}
}
}
return item;
}
public int getItemCount() {
return itemCount;
}
public int getMaxItemNumber() {
int max = 0;
if (itemCount > 0) {
for (int i = 0; i < itemCount; i++) {
DigitalFeature df = cameraList[i];
if (df.getItemNumber() > max) {
max = df.getItemNumber();
}
}
}
return max;
}
public double getValue() {
double total = 0.0;
for (int i = 0; i < getItemCount(); i++) {
total += getItem(i).getValueOfInventory();
}
return total;
}
public void sortItems() {
int n = getItemCount();
for (int search = 1; search < n; search++) {
for (int i = 0; i < n - search; i++) {
if (cameraList[i].getName().compareToIgnoreCase(
cameraList[i + 1].getName()) > 0) {
DigitalFeature temp = cameraList[i];
cameraList[i] = cameraList[i + 1];
cameraList[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;
}
}
above is my main section of code
__________________________________________________ ____________________
below is for my GUI
Code Java:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class InventoryGUI extends JFrame {
private static final long serialVersionUID = 1L;
private static final int NAVIGATION_MODE = 0;
private static final int ADDITION_MODE = 1;
private static final int MODIFICATION_MODE = 2;
private int currentMode;
JTextField itemNumber = new JTextField();
JTextField name = new JTextField();
JTextField unitsInStock = new JTextField();
JTextField unitPrice = new JTextField();
JTextField valueOfInventory = new JTextField();
JTextField restockingFee = new JTextField();
JTextField imageRes = new JTextField();
JButton next = new JButton("Next >");
JButton prior = new JButton("< Prior");
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");
JButton saveOrApply = new JButton("Save");
JButton searchOrCancel = new JButton("Search");
JTextField valueOfEntireInventory = new JTextField();
private Inventory inventory;
private int currentIndex = 0;
public InventoryGUI(Inventory inventory) {
super();
this.inventory = inventory;
setTitle("Inventory GUI - Part 6");
setBounds(0, 0, 400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createGUI();
pack();
setLocationRelativeTo(null); // center window
first.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showFirst();
}
});
prior.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showPrior();
}
});
next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showNext();
}
});
last.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showLast();
}
});
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addItem();
}
});
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteItem();
}
});
modify.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
modifyItem();
}
});
saveOrApply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (getCurrentMode() == NAVIGATION_MODE) {
saveInventory();
} else {
apply();
}
}
});
searchOrCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (getCurrentMode() == NAVIGATION_MODE) {
searchInventory();
} else {
cancel();
}
}
});
updateGUI();
}
protected void addItem() {
clearFields();
Integer newItemNumber = inventory.getMaxItemNumber() + 1;
itemNumber.setText(newItemNumber.toString());
name.requestFocus();
setCurrentMode(ADDITION_MODE);
}
protected void apply() {
int newItem = Integer.valueOf(itemNumber.getText());
String newName;
if ("".equals(name.getText().trim())) {
showErrorMessage("Please fill the Item Name.");
name.requestFocus();
return;
} else {
newName = name.getText();
}
int newUnits;
try {
newUnits = Integer.valueOf(unitsInStock.getText());
} catch (Exception e) {
showErrorMessage("Invalid value for the field Units In Stock.");
unitsInStock.requestFocus();
return;
}
double newUnitPrice;
try {
newUnitPrice = Double.parseDouble(unitPrice.getText());
} catch (Exception e) {
showErrorMessage("Invalid value for the field Unit Price.");
unitPrice.requestFocus();
return;
}
double newImageRes;
try {
newImageRes = Double.parseDouble(imageRes.getText());
} catch (Exception e) {
showErrorMessage("Invalid value for the field Image Resolution.");
imageRes.requestFocus();
return;
}
if (currentMode == ADDITION_MODE) {
DigitalFeature df = new DigitalFeature(newItem, newName, newUnits,
newUnitPrice, newImageRes);
inventory.addItem(df);
currentIndex = inventory.getItemCount() - 1;
} else if (currentMode == MODIFICATION_MODE) {
DigitalFeature df = inventory.getItem(currentIndex);
df.setName(newName);
df.setUnitPrice(newUnitPrice);
df.setImageRes(newImageRes);
df.setUnitsInStock(newUnits);
}
setCurrentMode(NAVIGATION_MODE);
updateGUI();
}
protected void cancel() {
setCurrentMode(NAVIGATION_MODE);
updateGUI();
}
private void clearFields() {
itemNumber.setText("");
name.setText("");
unitsInStock.setText("");
unitPrice.setText("");
valueOfInventory.setText("");
restockingFee.setText("");
imageRes.setText("");
}
private void createGUI() {
JPanel itemPanel = new JPanel(new GridLayout(0, 4, 5, 5));
itemPanel.add(new JLabel("Item Number:"));
itemPanel.add(itemNumber);
itemNumber.setEditable(false);
itemPanel.add(new JLabel("Item Name:"));
itemPanel.add(name);
itemPanel.add(new JLabel("Units In Stock: $"));
itemPanel.add(unitsInStock);
itemPanel.add(new JLabel("Unit Price: $"));
itemPanel.add(unitPrice);
itemPanel.add(new JLabel("Value of Inventory: $"));
itemPanel.add(valueOfInventory);
valueOfInventory.setEditable(false);
itemPanel.add(new JLabel("Restocking Fee: $"));
itemPanel.add(restockingFee);
restockingFee.setEditable(false);
itemPanel.add(new JLabel("Image Resolution:"));
itemPanel.add(imageRes);
itemPanel.add(new JLabel("Value of Entire Inventory: $"));
itemPanel.add(valueOfEntireInventory);
valueOfEntireInventory.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(prior);
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);
}
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;
}
private boolean isInventoryEmpty() {
if (inventory.getItemCount() == 0) {
JOptionPane.showMessageDialog(this, "The Inventory is Empty!");
return true;
}
return false;
}
protected void modifyItem() {
if (isInventoryEmpty()) {
return;
}
setCurrentMode(MODIFICATION_MODE);
}
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.");
}
}
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));
}
}
}
public void setCurrentMode(int currentMode) {
this.currentMode = currentMode;
switch (currentMode) {
case ADDITION_MODE:
case MODIFICATION_MODE:
first.setEnabled(false);
prior.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);
prior.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;
}
}
protected void setFieldsEditable(boolean editable) {
name.setEditable(editable);
unitsInStock.setEditable(editable);
unitPrice.setEditable(editable);
imageRes.setEditable(editable);
}
private void showErrorMessage(String message) {
JOptionPane.showMessageDialog(this, message, "Error",
JOptionPane.ERROR_MESSAGE);
}
protected void showFirst() {
if (isInventoryEmpty()) {
return;
}
currentIndex = 0;
updateGUI();
}
protected void showLast() {
if (isInventoryEmpty()) {
return;
}
currentIndex = inventory.getItemCount() - 1;
updateGUI();
}
private void showNext() {
if (isInventoryEmpty()) {
return;
}
if (currentIndex < inventory.getItemCount() - 1) {
currentIndex++;
updateGUI();
} else {
showFirst();
}
}
private void showPrior() {
if (isInventoryEmpty()) {
return;
}
if (currentIndex > 0) {
currentIndex--;
updateGUI();
} else {
showLast();
}
}
public void updateGUI() {
if (currentIndex != -1) {
DigitalFeature item = inventory.getItem(currentIndex);
itemNumber.setText(String.valueOf(item.getItemNumber()));
name.setText(item.getName());
unitsInStock.setText(String.valueOf(item.getUnitsInStock()));
unitPrice.setText(String.format("%.2f", item.getUnitPrice()));
valueOfInventory.setText(String.format("%.2f", item
.getValueOfInventory()));
restockingFee.setText(String
.format("%.2f", item.getRestockingFee()));
} else {
clearFields();
}
valueOfEntireInventory.setText(String.format("%.2f", inventory
.getValue()));
}
}
__________________________________________________ ______________________
last is for my logo
Code Java:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;
public class LogoPanel extends JPanel {
private static final long serialVersionUID = 1L;
public LogoPanel(int width, int height) {
super();
setPreferredSize(new Dimension(width, height));
}
@Override
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fill3DRect(0, 0, getWidth(), getHeight(), true);
int midX = getWidth() / 2;
int midY = getHeight() / 2;
g.setColor(Color.LIGHT_GRAY);
g.fillOval(midX - 100, midY - 25, 50, 50);
g.setColor(Color.BLACK);
g.setFont(new Font("Verdana", Font.BOLD, 24));
g.drawString("Camera Hut", midX - 70, midY + 10);
}
}
__________________________________________________ ____________________
Re: NullPointerException error
That's way too much code to wade through, but the Exception is telling you what's wrong: on line 187, you're dereferencing a null Object. You can't do that. Make sure that all of your variables reference an instance of something before you use them.
Re: NullPointerException error
Sorry about all the excess code I am new to posting in forums like this and wanted to ensure that I provided the right section of code. Thank-you for your reply though I do appreciate it very much.
Re: NullPointerException error
I've looked over it, but can't find it. At this point I'd put some println's in the sort method for cameraList[i] and i+1, as well as the value of i, above the if statement. I'd do it myself, but the workstation I'm at doesn't have a jdk installed :( , also is that a bubble sort? the variable name 'search' in the for loop is throwing me off.
Re: NullPointerException error
Your problem is in the digitalFeature constructor.
Code java:
public DigitalFeature(int item, String newName, int units, double price,
double string) {
super(item, name, units, price);
See if you can spot it without me having to tell you.
Re: NullPointerException error
jjeng ty I am looking at what you pointed out to see if I can figure it out.
junky are you referring to where I have the "newName" in the constructor?
Re: NullPointerException error
Kaching!
The parameter is called newName and yet you pass name to the super constructor. Since name (which is an inherited variable from the parent class) is null all you do is reset name to be null.
Re: NullPointerException error
Thank you Junky that was very helpful I appreciate the help very much. Now the only problem I am having is when I click my next and previous buttons and what not all the information in the boxes changes like its suppose to except the item name, for some reason it stays as sony. But again your assistance helped take a step in the right direction of getting this working right.