0

I'm getting this error from my code:

Exception in thread "main" java.lang.NullPointerException at MainClass.main(MainClass.java:20)

Could anyone identify the error, I think it has something to do with initializing my array?

MainClass.java

public class MainClass {


public static void main(String[] args) {

    //dummy vars to simulate user input
    double price = 2.75;

    //declare an array of wincalcs 
    WinCalc[] staging1;
    staging1 = new WinCalc[100];


    for (int x=0; x<staging1.length; x++ ) {
        staging1[x].price = price;
        staging1[x].quantity = x+1;
        staging1[x].calcTotal();    
    }



}

}

WinCalc.java

public class WinCalc {

public double price;
public double quantity;
public double total;

public WinCalc () {
    price= 0;
    quantity = 0;
    total = 0;
}

public void calcTotal() {
    this.total = price * quantity;
}

}

4 Answers 4

3

You forgot to create the objects

for (int x=0; x<staging1.length; x++ ) {
    staging1[x] = new WinCalc();   
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you allocate your array, it is initially populated with null entries. In order for it to contain actual objects, you must manually populate will newly allocated objects:

WinCalc[] staging1;
staging1 = new WinCalc[100];

for(int n = 0; n < 100; n ++)
{
    stanging1[n] = new WinClac();
}

This is because all objects in java are references which by default point to nowhere.

2 Comments

I like this answer the most because it explains WHY this is necessary
@Patashu Fix someone's code, it works for a day. Teach someone to fix their own code, it works for a lifetime. :)
0

Update your code with this:

public class MainClass {

public static void main(String[] args) {

    //dummy vars to simulate user input
    double price = 2.75;

    //declare an array of wincalcs 
    WinCalc[] staging1;
    staging1 = new WinCalc[100];


    for (int x=0; x<staging1.length; x++ ) {
        staging1[x] = new WinCalc(); 
        staging1[x].price = price;
        staging1[x].quantity = x+1;
        staging1[x].calcTotal();    
    }
}

Comments

0
Cases that we get NullPointerException are accessing/modifying the field of null object or accessing/modifying the slot of null as if it were an array or taking the length of null as if it were an array.
//Let us have a Person class 
public class Person {
          private String name;
          private int age;
    public Person(String name, int age) {
    this.name = name;
    this.age = age;
          }
    public String getName(){
      return name;
     }
   public int getAge(){
      return age;
    }
  public String toString(){
      return "[Name->"+ getName() +" ,Age->"+getAge()+"]";
     }
}
//The main class simulate collection of persons using array
import java.util.Arrays;
public class ListOfPersonIn {
public static void arrayManipulation() 
{
    Person[] persons=new Person[3]; // Array of Person to conatain 3 persons
              Person titi=new Person("Titi", 35);
    Person beti=new Person("Beti", 10);
    Person nati=new Person("nati", 18);
     // Display list of persons
     for(Person person:persons){
        System.out.println(person.toString());
      }
   //Double array size, copy the old value to the new array and add new persons 
    Person[]newPersons=copyArraySize(persons);
    System.out.println("Loop through a new Array ");
    for(Person person: newPersons){
        System.out.println(person.toString());
     }
    }
   // Private method to resize array, copy the old array to the new array and add new list of persons
private static Person [] copyArraySize(Person [] persons)
{
               Person[]newPersons=Arrays.copyOf(persons,  persons.length*2);
// newPersons[persons.length]=new Person("meti", 50); in this case we get NullPointerException   because the new array has length 6 but only 4 data is populated the reaming 2 indices are not populated i.e newArray[4] and newArray[5] are null value so it raised NullPointerException. Not to get NullPointerException  just populate all array indices with data 
     for(int i=persons.length;i< newPersons.length;i++){
          newPersons[i]=new Person("meti", 50);//duplicate data, array can’t maintain uniqueness like set 
        }
        return newPersons;
  }
  public static void main(String[] args) {
            arrayManipulation();
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.