I am new to Java and very frustrated. I have been trying to create a class of employees and a company class of employees. The company consists of an array of employees. The tester class, employees and company all compile, but when I execute the code I get a null pointer exception error. The tester class, employee and company class are below any help would be greatly appreciate and help me keep my sanity.
Thanks in advanced.
public class testsales { public static void main (String [] args) { KeyboardReader reader = new KeyboardReader(); company data = new company(); int [] sold = new int[3]; data.setSales(); System.out.println(data); } }
////////////////////////////////////////// publi c class Salesperson { KeyboardReader reader = new KeyboardReader(); public static final int WEEKS = 4; private String name=""; private int sales[];
public Salesperson() {name = "No Name"; sales = new int[WEEKS];
public void setName() {name = reader.readLine("Enter salesperson's name :"); }
public void setSales() { for ( int x = 0; x < sales.length;x++) sales[x] = reader.readInt("Enter sales for "+ name+"'s sales for week "+(x+1)); }
public String getName() { return name;}
public int[] getSales() { return sales; }
public int getLength() { return sales.length;}
public int totalSales() { int total=0; for ( int x = 0; x <sales.length;x++) total += sales[x]; return total; } public String toString () { String s; s=name+" "; for ( int x = 0; x < sales.length;x++) s += sales[x] +" "; s+= "\n"; return s; } }
///////////////////////////////////////////// public class company extends Salesperson { KeyboardReader reader = new KeyboardReader(); public static final int EMPLOYEES = 3; private String name=""; private Salesperson employees[];
public company() { employees = new Salesperson[EMPLOYEES]; name = " No Company Name"; }
public void setName() { name = reader.readLine("Enter company's name :"); }
public void setSales() { for ( int x = 0; x < employees.length;x++) { employees[x].setName(); for ( int y = 0; y < WEEKS;y++) employees[x].setSales(); } }
public String getName() { return name; }
public int companySales() { int total=0; for ( int x = 0; x < EMPLOYEES;x++) total += employees[x].totalSales( ); return total; }
public String toString () { String s; s=name+" "; for ( int x = 0; x < EMPLOYEES;x++) s += employees[x].toString() + " "; s+= "\n"; return s; } }
public company()
{
employees = new Salesperson[EMPLOYEES];
name = " No Company Name";
}
you should have
public company()
{
employees = new Salesperson[EMPLOYEES];
for (int i = 0; i < EMPLOYEES; ++i) {
employees[i] = new Salesperson();
}
name = " No Company Name";
}
When you create an array of objects, each element of the array is initially set to null. You have to set each element to an object explicitly.