繁体   English   中英

编程新手,带有ArrayList的Java.lang.NullPointerException

[英]New to programming, Java.lang.NullPointerException with ArrayList

我正在尝试解决这个问题几天,但没有成功。 这是代码:

import java.util.*;
import java.io.*;
public class Portefeuille {
private ArrayList<Woning> woningen;

public Portefeuille(){
    woningen = new ArrayList<Woning>();
}

public void voegToe(Woning w){
    if(woningen.contains(w)==false)
        woningen.add(w);
    else
        System.out.println(w.toString()+" komt al voor en is daarom niet toegevoegd.");
}

public ArrayList<Woning> woningenTot(int maxprijs){
    ArrayList<Woning> totaal = new ArrayList<Woning>();
    for(int i=0; i<woningen.size(); i++){
        if((woningen.get(i)).KostHooguit(maxprijs))
            totaal.add(woningen.get(i));
    }
    return totaal;
}

public static Portefeuille read(String infile){
    Portefeuille woningen = new Portefeuille();
    try
    {
        FileReader file = new FileReader(infile);
        Scanner sc = new Scanner(file);
        int aantalwoningen = sc.nextInt();
        for(int i=0; i<aantalwoningen; i++){
            Woning woning = Woning.read(sc);
            woningen.voegToe(woning);
        }
        System.out.println(woningen.toString());
        sc.close();
    } catch(Exception e){
        System.out.println(e);
      }
 return null;
 }
}

这是主文件

    import java.util.*;
    public class Test2 {
public static void main(String[] args){

    Portefeuille bestand = Portefeuille.read("in.txt");
    ArrayList<Woning> WTot = bestand.woningenTot(21500);

}
}

我得到的错误是:Test2.main(Test2.java:6)处的线程“ main”中的异常java.lang.NullPointerException

如果有人至少可以指出我正确的方向,我将不胜感激。

谢谢,

Jaspreet

最终尝试在指向空值的引用而不是对象上调用方法时,将得到NullPointerException。 在您的情况下,将为bestand.woningenTot(21500); 因为对Portefeuille.read("in.txt");的调用Portefeuille.read("in.txt"); 始终返回null

您的Portefeuille.read("in.txt")返回null而不是woningen

    public static Portefeuille read(String infile){
        Portefeuille woningen = new Portefeuille();
        try
        {
            FileReader file = new FileReader(infile);
            Scanner sc = new Scanner(file);
            int aantalwoningen = sc.nextInt();
            for(int i=0; i<aantalwoningen; i++){
                Woning woning = Woning.read(sc);
                woningen.voegToe(woning);
            }
            System.out.println(woningen.toString());
            sc.close();
        } catch(Exception e){
            System.out.println(e);
          }
     return woningen ;
     }
    }

您在静态读取函数中返回null ...因此您无法在第6行访问该对象。 尝试返回woningen

方法Portefeuille.read始终返回null。 您需要返回正在创建的Portefeuille。

旁注:-总是在finally部分中调用close-使用增强的外观,而不是普通的for循环。 像for(String s:collectionOfStrings)-尝试使用接口而不是具体的类进行编程。 例如:使用List而不是ArrayList

好吧,在我看来

public static Portefeuille read(String infile) 

始终返回null。 也许应该有一个

return woningen;

在sc.close()之后;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM