Question

So I'm trying to read a local .txt file and then print out the file using the toString method. I have to have two files, the main and an additional class. I have established my toString in the second class and now I'm trying call it in the main. Here's the example code:

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;
    }
}

My while loop needs to read the line (I'm also lost here). First the city as a string and then the latitude and longitude as doubles. I'm tripped up in this regard because I'm required to do this and print out the file using the toString. I don't know how to do this without using an array. Can somebody point me in the right direction?

Était-ce utile?

La solution

Assuming your text file has city information on each line, is this what you're after?

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
}

Autres conseils

input.nextLine() returns a String containing the line, which you can then print or convert into a Locations object as you see fit.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top