【发布时间】: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