【问题标题】:Using toString method without an array?使用没有数组的 toString 方法?
【发布时间】:2014-05-02 00:02:09
【问题描述】:

所以我尝试读取本地 .txt 文件,然后使用 toString 方法打印出该文件。我必须有两个文件,主类和附加类。我已经在第二堂课中建立了我的 toString,现在我正在尝试在主课中调用它。下面是示例代码:

public class Hmwk {

    public static void main(String[] args) {
        String fileName = "input.txt";
        File inputFile = new File(fileName);

        try {
            Scanner input = new Scanner(inputFile);
            while(input.hasNextLine()) {

            }
            input.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

public class Locations {
    private String cityName;
    private double latitude;
    private double longitude;

    public Locations(String theCityName, double latitude, double longitude){
        setCityName(theCityName);
        setLat(latitude);
        setLong(longitude);
    }
    public void setCityName(String thecityName) {
        thecityName = cityName.trim();
    }
    public void setLat(double latitude) {
        this.latitude = latitude;
    }
    public void setLong(double longitude) {
        this.longitude = longitude;
    }       
    public String getCityName() {
        return cityName;        
    }
    public double getLatitude() {
        return latitude;
    }
    public double getLongitude() {
        return longitude;
    }

    public String toString() {
        String result = String.format("City: %s (%d , %d )", cityName, latitude,   longitude);
        return result;
    }
}

我的 while 循环需要读取该行(我在这里也迷路了)。首先将城市作为字符串,然后将纬度和经度作为双倍。我在这方面被绊倒了,因为我需要这样做并使用 toString 打印出文件。如果不使用数组,我不知道如何做到这一点。有人能指出我正确的方向吗?

【问题讨论】:

  • 在发布问题之前格式化您的代码。

标签: java arrays file methods tostring


【解决方案1】:

假设你的文本文件的每一行都有城市信息,这是你想要的吗?

while(input.hasNextLine()){

     String cityName = input.next();
     double latitude = input.nextDouble();
     double longitude = input.nextDouble();
     Locations loc = new Locations(cityName, latitude, longitude);

     System.out.println(loc); // automatically calls Locations's toString method
}

【讨论】:

    【解决方案2】:

    input.nextLine() 返回包含该行的String,然后您可以根据需要打印或转换为Locations 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      • 2021-07-18
      相关资源
      最近更新 更多