Hello everyone at JPF!
I am completey new to Java, in fact I am completely new to lower level languages full stop. I have a reasonable amount of experience with high level languages namely MatLab so I understand programming concepts but not the software engineering of it all. I tell you this so you go in knowing it's most probably a stupid question...
Project Outline:
I am building a turn based game for which I am laying down some foundations to get some understanding
components of the project that are causing me problems:
class unit
subclass infantry extends unit
class army
public class unit { // vars public int posX,posY,posZ; public String type; // constructor public unit(int x, int y, int z, String t) { this.posX = x; this.posY = y; this.posZ = z; this.type = t; } // methods // movement public void move(int moveX, int moveY, int moveZ) { this.posX = this.posX + moveX; this.posY = this.posY + moveY; this.posZ = this.posZ + moveZ; } public void printStates() { System.out.println("unit type:"+this.type+"posX"+this.posX+" posY:"+this.posY+" posZ:"+this.posZ); } }public class infantry extends unit{ static String infantryType = "Infantry"; // stance 0=standing,1=crouch,2=prone public int stance,accuracy; // accuracy base describes the accuracy of a unit given a stance public int accuracyBase[] = new int[3]; public infantry(int x, int y, int z) { super(x, y, z, infantryType); this.accuracyBase[0]=1; this.accuracyBase[1]=2; this.accuracyBase[2]=3; // TODO Auto-generated constructor stub } public void changeStance(int newStance) { this.stance = newStance; } public void update() { this.accuracy = accuracyBase[this.stance]; } }
public class army { public infantry[] armyInf; public infantry[] armyUni; public army(int ninf,int nveh) { infantry[] armyInf = new infantry[ninf]; unit[] armyUni = new unit[nveh]; for (int i = 0;i<ninf;i++) { armyInf[i] = new infantry(0,0,1); } for (int j = 0;j<nveh;j++) { armyUni[j] = new unit(0,0,0,"vehicle"); } } }
so My main function is below. I will mention now that there are no compilation errors and the calls to unit classes and infantry classes work and the printstates works also.
public class emwar { public static void main(String[] args) { army army1 = new army(3,1); unit unit1 = new unit(10,10,10,"foot"); unit unit2 = new unit(0,0,0,"foot"); unit1.move(1,1,1); unit1.printStates(); unit2.move(20,20,0); unit2.printStates(); infantry infant1 = new infantry(0,0,0); infant1.printStates(); army1.armyInf[0].printStates(); }
The error when this is run is:
Exception in thread "main" java.lang.NullPointerException at cis.emwar.main(emwar.java:30)
Note: line 30 coincides with the army1.armyInf[0].printStates(); call
I have seen the thread here and have made the modification in class army to match this, which [clearly] has not worked for me.
All help greatly appreciated!
Keep up the Fun!