This site requires JavaScript, please enable it in your browser!
Greenfoot back
mahimahi42
mahimahi42 wrote ...

2011/3/9

Problem with java.lang.NullPointerException

mahimahi42 mahimahi42

2011/3/9

#
Hi all, I have to do a research project for my Research class, and am programming it in Greenfoot. However, I'm having some difficulties. I have a method that prints out the number of Organism.class in the world along with the act cycle. However, I only want it to print every 100th act cycle, but I keep getting a null pointer exception. Here's the offending code: public void printNumberOfOrganisms() { File f = new File("output.txt"); String curDir = f.getAbsolutePath(); String strFilePath = curDir; try { if (everyHundreth() % 500 == 0) { FileOutputStream fos = new FileOutputStream(strFilePath, true); String printCycle = Long.toString(((Desert) getWorld()).printCycle()); String strContent = Long.toString(numberOfOrganisms()); strContent = strContent + " " + printCycle; String newLine = System.getProperty("line.separator"); fos.write(strContent.getBytes()); fos.write(newLine.getBytes()); fos.close(); } } catch(FileNotFoundException ex) { System.out.println("FileNotFoundException: " + ex); } catch(IOException ioe) { System.out.println("IOException: " + ioe); } } public double everyHundreth() { double x = ((Desert) getWorld()).printCycle(); return x; } And the error: java.lang.NullPointerException at Organism.everyHundreth(Organism.java:384) at Organism.printNumberOfOrganisms(Organism.java:358) at Organism.act(Organism.java:109) at greenfoot.core.Simulation.runOneLoop(Simulation.java:346) at greenfoot.core.Simulation.run(Simulation.java:178) Any help would be appreciated!
spaceblue spaceblue

2011/3/9

#
Can you tell us what line 384 is exactly? You can display line numbers in greenfoot by going to Options>Preferences in the Editor menu and then checking "Show Line Numbers." Alternatively, you can use Tools>Go to line (Ctrl L) and go to line 384.
mahimahi42 mahimahi42

2011/3/9

#
Line 384 is: double x = ((Desert) getWorld()).printCycle(); The method printCycle() in Desert is: public long printCycle() { long x = printCounter++; return x; }
mik mik

2011/3/10

#
If that line gives you a NullPointer, then that means that getWorld() returns null. getWorld() returns null if the actor is not in the world. (getWorld()essentially says "Give me my world" and in that case the actor does not have a world.) So either your actor has not been inserted into the world, or it has been removed from it. So make sure that printNumberOfOrganisms() does not get called while the actor is not in the world.
You need to login to post a reply.