java - 尝试使用文件输入从数组创建对象时我做错了什么
问题描述
我目前正在学习 Java OOP,但很难理解为什么我会继续出错。
我的船课如下:
//Boats
public class Boats {
String Name;
int age;
int length;
Boats(String Name){
this.Name = Name;
this.age = age;
this. length = length;
}
public void setName(String name){
this.Name = name;
}
public void returnBoatInfo(){
System.out.println("Boat "+Name+" is"+age+" years old "+" and "+length+" feet long");
}
}
当我尝试将其声明为对象数组并使用文件创建新对象时。似乎从未创建过任何对象。主要如下:
//Main
Boats[] fleet = new Boats[3];
Scanner readFile = new Scanner(new File("boats.txt"));
/*
fleet[0] = new Boats("Destiny",25,30);
fleet[1] = new Boats("Sea Monkey",15,25);
fleet[2] = new Boats("Morning Star",35,42);
for(int i=0;i<3;i++){
fleet[i].returnBoatInfo();
//this works
}
*/
for(int i = 0;fleet.length<i;i++){
fleet[i].Name = new Boats(readFile.nextLine());
fleet[i].returnBoatInfo();
System.out.println("File has been read "+ readFile.nextLine());
break;
}
如果我尝试循环并打印每个对象的 returnBoatInfo 语句,我将永远得不到任何东西。我确定我在这里遗漏了一些东西,任何有助于理解这一点的帮助都会非常感激。
解决方案
舰队[i].Name = new Boats(readFile.nextLine());
fleet[i].Name
是一个字符串,new Boats(readFile.nextLine())
是一个船对象。
尝试这个:
fleet[i].Name = readFile.nextLine();
readFile.nextLine()
将返回一个字符串,因此您可以使用它来填充Name
属性。
此外,请按照评论中的说明更改您的状况。
推荐阅读
- jmeter - Jmeter - 如何将 forEach 循环的每个成员放入变量中
- c# - 统一问题此脚本不继承可以管理脚本的本机类
- git - 为什么我不能使用 gith bash 推送到 github 存储库?
- android - Sinch API 失败
- javascript - 如何使用 react-native 在更新 asyncstorage 时更新 app.js
- excel - HighlightColorIndex 显示颜色不正确
- angular - AES 加密在前端(Angular)中不起作用
- questdb - Questdb 与 Grafana 8 兼容吗?
- python-3.x - 是否可以选择安装tensorflow的文件?
- python - 需要能够执行多个项目的功能,但它不能工作,为什么?