我目前正在学习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语句,我将一无所获。我确定我在这里缺少任何东西,希望能帮助您理解更好的信息。
fleet [i] .Name =新船(readFile.nextLine());
[fleet[i].Name
是字符串,new Boats(readFile.nextLine())
是Boat对象。
尝试一下:
fleet[i].Name = readFile.nextLine();
[readFile.nextLine()
将返回一个字符串,因此您可以使用它来填充Name
属性。
也请按照评论中的说明更改您的条件。