java - 为什么在此代码片段中尝试分配后对象仍然为空?
问题描述
这里的任务是从文件中读取一些行并创建“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);
}
解决方案
推荐阅读
- ios - Xcode 中大约 100 个错误,未定义符号。在我的统一项目中
- google-cloud-sql - 如何从 Google App Maker 连接到 Google Cloud SQL 数据库作为外部 mysql 数据库?
- reactjs - React中的预增量运算符?
- django - 如何使用 heroku 将新的 pip 包添加到已部署的应用程序
- javascript - 输入值时,Knockout observable 错误地改变了数学计算的结果
- python - 如何根据坐标更新numpy数组
- stata - 不区分大小写地加载 Excel 文件表
- html - 在另一个矩形中创建一个矩形并定位元素
- django - 如何在 Django 中使用电子邮件登录?
- python-3.x - 自定义损失的梯度