首页 > 解决方案 > 为什么在此代码片段中尝试分配后对象仍然为空?

问题描述

这里的任务是从文件中读取一些行并创建“Plant”类型的对象并将它们添加到 ArrayList“plants”中,这是 Plant 类中的一个字段。我应该让引用 tempPlant 引用“Plant”类的特定子实例。

每次我从文件中读取并尝试创建类 Plant 的实例时,它都会失败。

我也尝试使用缓冲阅读器,但它并没有很好地锻炼,并且似乎代码会变得更加冗长(这是我试图避免的 Java 中的常见情况)。请帮忙。

更新:该文件预计只有“类型”的小写条目。每当我运行它时,它都会从文件中读取它们,但它不执行此检查if ('p'== type)

public static void main(String[] args) throws FileNotFoundException {

    Planet zelda = new Planet();
    File myFile = new File("in1.txt");
    Scanner sc = new Scanner(myFile);

    int numOfLines = sc.nextInt();
    int days;

    for (int i = 0; i < numOfLines; i++) {
        String name = sc.next();
        String typeStr = sc.next();
        char type = typeStr.charAt(0);
        int nutrients = sc.nextInt();
        System.out.println(name);
        System.out.println(type);
        System.out.println(nutrients);


        Plant tempPlant = null;
        if ('p'== type) {
            tempPlant = new Puffs(name, nutrients);
        } else if ('b'== type) {
            tempPlant = new Parabush(name, nutrients);
        } else if ('d' == type) {
            tempPlant = new Deltatree(name, nutrients);
        }
        zelda.addPlant(tempPlant);

    }
    days = sc.nextInt();
    sc.close();

    zelda.start(days);

}

标签: javafile

解决方案


推荐阅读