Results 1 to 4 of 4
Thread: Help @ Java
- 05-11-2011, 09:40 AM #1
Member
- Join Date
- Jan 2011
- Posts
- 3
- Rep Power
- 0
Help @ Java
Java Code:package banksystem; import java.io.File; public class test { static Person[] p; public static void main(String[] args) { final File f = new File("bankomat.dat"); BankSystem bs = new BankSystem(); setUPUser("Anders", "300", 1); setUPUser("Stig", "100", 1); bs.saveDATFile(f); } protected static int checkID(int newID) { [B]for (Person np : p)[/B] { if (newID == np.getID()) { checkID(newID + 1); } else { return newID; } } return newID; } protected static void setUPUser(String newMoney, String newName, int newID) { p[0] = new Person(newName, newMoney, checkID(newID)); } private void typeUsers() { for (Person np : p) System.out.println(np.toString()); } }Throws me nullpointerexception, why?Java Code:package banksystem; import java.io.Serializable; import java.util.ArrayList; public class Person implements Serializable { static int id; ArrayList<String> a; public Person() { setID(1); this.a = new ArrayList<String>(); setName("Per"); setMoney("100"); } public Person(String newName) { setID(BankSystem.getK()); this.a = new ArrayList<String>(); setName(newName); setMoney("0"); } public Person(String newName, String newMoney, int newID) { this.a = new ArrayList<String>(); setName(newName); setMoney(newMoney); setID(newID); } protected static void setID(int setNewID) { id = test.checkID(setNewID); } private void setName(String name) { a.add(0, name); } private void setMoney(String money) { a.add(1, money); } public int getID() { return id; } public String getName() { return a.get(0); } public String getMoney() { return a.get(1); } @Override public String toString() { return ("The name of ID " + getID() + " is: " + getName() + ". " + getName() + " has " + getMoney() + " Swedish kronor."); } }
Exception in thread "main" java.lang.NullPointerException
at banksystem.test.checkID(test.java:22)
at banksystem.test.setUPUser(test.java:39)
at banksystem.test.main(test.java:15)
Java Result: 1
- 05-11-2011, 10:01 AM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
It looks like you never initialize p, it's just an array declaration without an initialization.
There is also quite a few other problems with this code.
- 05-11-2011, 10:50 AM #3
the Person[] p is never initialized, but even if you initialize this array the first time you make a call to checkID there are no elements in the array so the np.getID() will cause the NullPointerException. make sure np.length > 0 is true!
Last edited by DarrylBurke; 05-11-2011 at 11:07 AM. Reason: Removed quoted spam links
- 05-11-2011, 11:10 AM #4


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks