首页 > 解决方案 > 尝试使用文件输入从数组创建对象时我做错了什么

问题描述

我目前正在学习 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 语句,我将永远得不到任何东西。我确定我在这里遗漏了一些东西,任何有助于理解这一点的帮助都会非常感激。

标签: javaoop

解决方案


舰队[i].Name = new Boats(readFile.nextLine());

fleet[i].Name是一个字符串,new Boats(readFile.nextLine())是一个船对象。

尝试这个:

fleet[i].Name = readFile.nextLine();

readFile.nextLine()将返回一个字符串,因此您可以使用它来填充Name属性。

此外,请按照评论中的说明更改您的状况。


推荐阅读