【问题标题】:Exception in thread "main" java.lang.NullPointerException on Java ArrayJava Array 上的线程“main”java.lang.NullPointerException 中的异常
【发布时间】:2013-05-03 03:52:56
【问题描述】:

我的代码出现了这个错误:

线程“main”中的异常 java.lang.NullPointerException 在 MainClass.main(MainClass.java:20)

谁能找出错误,我认为它与初始化我的数组有关?

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;
}

}

【问题讨论】:

    标签: java arrays nullpointerexception


    【解决方案1】:

    你忘了创建对象

    for (int x=0; x<staging1.length; x++ ) {
        staging1[x] = new WinCalc();   
        // ...
    }
    

    【讨论】:

      【解决方案2】:

      当您分配数组时,它最初会填充空条目。为了让它包含实际的对象,您必须手动填充新分配的对象:

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

      这是因为 java 中的所有对象都是默认指向无处的引用。

      【讨论】:

      • 我最喜欢这个答案,因为它解释了为什么这是必要的
      • @Patashu 修复某人的代码,它可以工作一天。教别人修复自己的代码,它可以用一辈子。 :)
      【解决方案3】:

      用这个更新你的代码:

      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();    
          }
      }
      

      【讨论】:

        【解决方案4】:
        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();
             }
        }
        

        【讨论】:

          猜你喜欢
          • 2013-11-21
          • 1970-01-01
          • 1970-01-01
          • 2016-02-05
          • 2012-12-09
          • 1970-01-01
          • 2017-03-27
          • 2023-03-10
          • 2013-04-30
          相关资源
          最近更新 更多