NullPointerException- urgent
I'm trying to get a bit of code to work for me. I have an array of objects, a catalogue object that contains this array, and a main to drive it all. There is also an object to control file IO from a formatted file.
Where I'm completely baffled is the main reads the file, passes the required data to the catalogue which then creates the object as its all supposed to, and puts the 2 objects into the array- I've tested the data at all points: the file IO, the main, the catalogue, and the object in the array- but when the catalogue prints the array on screen and back to the file it tells me the 2nd object doesn't exist.
I've also tested the index which determines the loop to print the data out and it's accurate.
I'm at my wits end on this one and tearing my hair out- I was supposed to have been finished this 3 days ago! GRR!
Any ideas out there guys?
[895 byte] By [
Da_Rocka] at [2007-10-2 21:07:07]

Your problem is truly mysterious. Perhaps you should try www.psychicdebuggers.com.
> I'm trying to get a bit of code to work for me.
Wow, I need such code as well!
> I have an array of objects, a catalogue object that
>
> ...
>
> I'm at my wits end on this one and tearing my hair
> out- I was supposed to have been finished this 3 days
> ago! GRR!
>
> Any ideas out there guys?
Did you get compiler/runtime errors? Did you debug your code? Put some System.out.println()'s in your code to see what happens with your variables.
Post your code or errors here and explain your problem again. When posting code, use code-tags: http://forum.java.sun.com/help.jspa?sec=formatting
Oh, next time please don't flag your posts as "urgent"; it's rude.
Sorry about the urgent but as you can see I'm running out of time in a major way. I'm already 3 days behind and I've got alot more work to do.
I've tried the System.out.println() method, but as I said the object exists and is well- the data gets thru, it just spits the dummy during runtime with a NullPointerException during a loop where it shouldn't be a problem.
So we have this small piece of code:
public class main
{
public static void main()
{
//initialisation, take user input etc
}
fileRead(fileName)
{
//more code in here to read formatted file, etc
ToolCatalogue.addTool(toolType, qty, price);
}
}
public class ToolCatalogue
{
private final int MAXRECORDS = 20;
private int index;
private int record;
private String toolType = new String();
private String qty = new String();
private String price = new String();
private Tools[] toolRecord = new Tools[MAXRECORDS];
private String file = "";
private String fileName;
public void toolCatalogue()
{
index = 0;
}
public void addTool(String aToolType, String aQty, String aPrice)
{
System.out.println(aToolType + aQty + aPrice);
if (index < MAXRECORDS)
{
toolRecord[index] = new Tools(aToolType, aQty, aPrice);
index++;
}
else
System.out.println("Can't add more records. Catalogue is full: "
+ MAXRECORDS + " records.");
index++;
}
public String getTool(int aToolRecord)
{
record = aToolRecord;
String details = toolRecord[record].getToolDetails();
return details;
}
public void deleteTool(int aToolRecord)
{
record = aToolRecord;
toolRecord[record].equals(null);
System.out.println("Record deleted");
}
public void printCatalogue(String aFileName)
{
fileName = aFileName;
record = 0;
System.out.println("Record#\tTool Name\tQuantity\tCost/Item (AUD)\n");
while (record < index)
{
System.out.println(record + "\t"+ toolRecord[record].getTool() + "\t\t"
+ toolRecord[record].getQty() + "\t\t" + toolRecord[record].getPrice());
file = file + toolRecord[record].getToolDetails() + ";";
record++;
}
FileIO filing = new FileIO();
filing.fileWriting(file, fileName);
}
}
Essentially the problem occurs when the printCatalogue() method is called.
In my testing I have 2 records which are entered into the array, the objects are created successfully as I have tested this already using System.out.println() on object creation. The loop in printCatalogue() method works the first round but as soon as record = 1 it fails with a null pointer exception.
I can't work it out- I've searched high and low for answers, I've changed parameters like record <= index. It seems to mystify a lot of people...
Anyway I do thank you if you can help.
When the JVM throws an exception, you should look at the stack trace. It tells you the name of the class and the line number at which the exception was thrown. Turn on line numbers in your editor, go to the line at which the NPE was thrown, look at any objects on that line and think hard about why they might be null.
This is one of the easiest problems to debug. You should be able to figure it out quickly.
As for the rest of your code, I don't understand why you have tool type, quantity, and price but no Tool class. You addTool to a catalog, yet the parameter is not a Tool type? Java is an object-oriented language. Start writing as if it were one.
You have member variables in your ToolCatalog that don't make any sense. Why do you need file and fileName? What's up with those calls to new String()? Terrible idea.
Your code should be far simpler. Think about it some more. Start with that Tool class.
%
Thats the first thing I did- and the problem is is that it isn't null. There IS data in the Tool object.
BTW- I didn't want to swamp with code so not all of it is in there, only the part where the problem lies (as far as I can see). I don't like programming in any way other than with OO as I have found out in my short programming life.
However, you will have to excuse some of the mess in the code as I haven't finished cleaning it up yet and getting rid of uneeded variables and such.
At a first glance, this might be causing the problem:
public void toolCatalogue()
{
index = 0;
}
shouldn't that be a constructor? Now your index is never initialised. A construcor would look like this:
public ToolCatalogue()
{
index = 0;
}
Good luck.
Thanks- I'm gonna need it.
Thats a good point- I did miss that one, thanks. It didn't fix the problem though, I'm afraid.
I think I have ghosts in my system coz this one is just tooo spooky!
If I create an object containing data in an array though, if it shows the data being there using System.out.println() the object shouldn't disappear should it? Only if the array is wiped- and then all other objects would be gone too. So if I enter 2 objects into this array (checking existence as above) and the 2nd turns null, then..... what could be wrong? Objects are 0 and 1, the loop calls 0 first which is ok, then 1 and fails.
Am I accurate in these statements?
> Now your index is never initialised.
It is initialized to 0 by default which is the same value assigned to it
by that feeble attempt of a constructor so that can't be the problem. My
guess is that the code the OP didn't show is to blame ...
kind regards,
Jos ( but it's Saturday so I'm too lazy to dig into that ;-)
JosAHa at 2007-7-13 23:52:43 >

> Thanks- I'm gonna need it.
>
> Thats a good point- I did miss that one, thanks. It
> didn't fix the problem though, I'm afraid.
>
> I think I have ghosts in my system coz this one is
> just tooo spooky!
Mistake #1: Students assume that it's "ghosts" and "spooky" stuff. Not so. You are the one that puts the bugs in your code. The machine is only doing what you told it to do. If it's not behaving the way you think it should, either your assumptions are incorrect or your code is wrong. You should doubt yourself first, last, and always.
> If I create an object containing data in an array
> though, if it shows the data being there using
> System.out.println() the object shouldn't disappear
> should it? Only if the array is wiped- and then all
> other objects would be gone too. So if I enter 2
> objects into this array (checking existence as above)
> and the 2nd turns null, then..... what could be
> wrong? Objects are 0 and 1, the loop calls 0 first
> which is ok, then 1 and fails.
>
> Am I accurate in these statements?
No, you're wrong. Your code is incorrect.The machine is not persecuting you.
The proper signature for overriding main is:
public static void main(String [] args)
Is that what you have? If not, fix it. There are lots of other things wrong with your stuff, too. Go find them.
%
PS - Here's what my Tool class looks like:
package tool;
import java.io.Serializable;
/**
* Simple Tool class
* Created by IntelliJ IDEA.
* User: Michael
* Date: May 27, 2006
* Time: 8:38:42 AM
* To change this template use File | Settings | File Templates.
*/
public class Tool implements Serializable
{
public static final String DELIMITER = ",";
private final String type;
private final int quantity;
private final double price;
public Tool()
{
this("", 0, 0.0);
}
public Tool(String type, int quantity, double price)
{
if (quantity < 0)
throw new IllegalArgumentException("quantity cannot be negative");
if (price < 0.0)
throw new IllegalArgumentException("price cannot be negative");
if (type == null)
this.type = "";
else
this.type = ((type.trim().length() == 0) ? "" : type);
this.quantity = quantity;
this.price = price;
}
public static Tool valueOf(String record) throws NumberFormatException
{
String [] tokens = record.split(DELIMITER);
String type= ((tokens.length > 0) ? tokens[0] : "");
int quantity= ((tokens.length > 1) ? Integer.parseInt(tokens[1]) : 0);
double price= ((tokens.length > 2) ? Double.parseDouble(tokens[2]) : 0.0);
return new Tool(type, quantity, price);
}
public static Tool valueOf(String type, int quantity, double price)
{
return new Tool(type, quantity, price);
}
public String getType()
{
return type;
}
public int getQuantity()
{
return quantity;
}
public double getPrice()
{
return price;
}
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass()) return false;
Tool tool = (Tool) o;
if (Double.compare(tool.price, price) != 0) return false;
if (quantity != tool.quantity) return false;
if (!type.equals(tool.type)) return false;
return true;
}
public int hashCode()
{
int result;
long temp;
result = type.hashCode();
result = 31 * result + quantity;
temp = price != +0.0d ? Double.doubleToLongBits(price) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
public String toString()
{
return"Tool{"+
"type='"+type+'\''+
", quantity="+quantity+
", price="+price+
'}';
}
}
Works nicely with my ToolCatalog.
> public void addTool(String aToolType, String aQty,
> String aPrice)
>{
>System.out.println(aToolType + aQty + aPrice);
>if (index < MAXRECORDS)
>{
>
> toolRecord[index] = new Tools(aToolType, aQty,
> aPrice);
> index++; // < look the index got incremented!
>
>}
>
>else
> System.out.println("Can't add more records.
> Catalogue is full: "
>+ MAXRECORDS + " records.");
>index++; // look! it got incremented again!
kind regards,
Jos
JosAHa at 2007-7-13 23:52:43 >

> Jos ( but it's Saturday so I'm too lazy to dig into that ;-)Also see my previous reply; I must be a loony ;-)kind regards,Jos
JosAHa at 2007-7-13 23:52:43 >

$#%&*!!!!Thanks for that- sometimes all it takes is another pair of eyes and a fresh look. When you've been working on something for so long it gets damned monotonous.Cheers dude- it all works(Bloody ony one line of code- grrr!)
> $#%&*!!!!
>
> Thanks for that- sometimes all it takes is another
> pair of eyes and a fresh look. When you've been
> working on something for so long it gets damned
> monotonous.
>
> Cheers dude- it all works
> (Bloody ony one line of code- grrr!)
It might "work", but it's still not good code. Come back and ask if you'd like to learn something.
%
> It is initialized to 0 by default which is the same value assigned to it
> by that feeble attempt of a constructor so that can't be the problem. My
> guess is that the code the OP didn't show is to blame
> ...
>
> kind regards,
>
> Jos ( but it's Saturday so I'm too lazy to dig into that ;-)
Thanks for the correction Jos.
Regards,
Bart.
Actually I did. I learnt a few good tricks from what you posted.
I might be crude with OO at first, but I started thinking OO before I was taught how to do it, so I had to learn about encapsulation and stuff as an after thought.
Any other tips forthcoming would be appreciated- I'm still working on eloquence :).
Out of curiosity- how would you use a reference to an object within one instance from another class? Or isn't it possible? I wanted to use it in this project but I couldn't make it work- not with the time I have to do this anyway- but I am still curious.
> $#%&*!!!!
>
> Thanks for that- sometimes all it takes is another
> pair of eyes and a fresh look. When you've been
> working on something for so long it gets damned
> monotonous.
>
> Cheers dude- it all works
> (Bloody ony one line of code- grrr!)
That's because your code is a bit *ahem* messy.
Here's a (slightly) better approach:
Tool.javapublic class Tool {
private String type;
private int quantity;
private double price;
public Tool(String type, int quantity, double price) {
this.type = type;
this.quantity = quantity;
this.price = price;
}
// The rest of your methods here...
public String toString() {
return "[type = "+type+", quantity = "+quantity+", price = $"+price+"]";
}
}
ToolCatalogue.javapublic class ToolCatalogue {
private final int MAXRECORDS;
private int numberOfTools;
private Tool[] toolArray;
public ToolCatalogue(int maxRecords) {
MAXRECORDS = maxRecords;
toolArray = new Tool[MAXRECORDS];
numberOfTools = 0;
}
public void addTool(Tool tool) {
// First you should check if the array isn't full yet
toolArray[numberOfTools] = tool;
numberOfTools++;
}
public Tool getTool(int index) {
// You should check if 'index' is between 0 and 'numberOfTools'-1
return toolArray[index];
}
public void deleteTool(int index) {
// You should check if 'index' is between 0 and 'numberOfTools'-1
toolArray[index] = null;
numberOfTools--;
// And now you you should check if there are any Tools to the right
// of the tool you just deleted and shift every tool one place to
// the left
}
public String toString() {
StringBuffer buffer = new StringBuffer();
final String NEWLINE = System.getProperty("line.separator");
for(int i = 0; i < numberOfTools; i++) {
buffer.append(toolArray[i]);
buffer.append(NEWLINE);
}
return buffer.toString();
}
}
And a class to test it, Main.javapublic class Main {
public static void main(String[] args) {
ToolCatalogue catalogue = new ToolCatalogue(10);
catalogue.addTool(new Tool("Hammer", 10, 6.99));
catalogue.addTool(new Tool("Bone crusher", 3, 6.66));
catalogue.addTool(new Tool("Bigger hammer", 2, 16.99));
System.out.println(catalogue);
}
}
Good luck.
> Any other tips forthcoming would be appreciated- I'm
> still working on eloquence :).
Maybe you should use a List instead of an array for your Catalogue.
If you delete an object from it, it will be really gone instead of leaving an
ugly null hole in the middle of that array. If you add another one to it, you
can simply add it to the List. Just for starters ;-)
kind regards,
Jos
> Maybe you should use a List instead of an array for your Catalogue.
> If you delete an object from it, it will be really gone instead of leaving an
> ugly null hole in the middle of that array. If you add another one to it, you
> can simply add it to the List. Just for starters ;-)
>
> kind regards,
>
> Jos
(Of course) you're right, Jos. But I think this is where the "we have to use an array"-part kicks in.
; )
> (Of course) you're right, Jos. But I think this is where the "we have to
> use an array"-part kicks in. ; )
I guess I was just lucky today because I tried to answer another question
lately where things had to be sorted where not even arrays were allowed.
I didn't even dare to mention the List interface ;-)
kind regards,
Jos