user3371750
user3371750

Reputation:

Formatting data read in from text file

I have an object Location which takes parameters String name, int xCoordinate, int yCoordinate. I have the following text file from which to read in the values and turn them into Location objects.

Location: Italy 65 120
Location: Spain 20 100
Location: France 130 60
Location: England 160 140
Location: Scotland 65 100
Location: Hungary 110 120
Location: Ireland 20
120

Location: Russia 40 10
Location: America 90 15
Location: Greece 

39 23
Location: India 49 5
Location: Japan 11 20
Location: Africa 110
100

Location: Norway 22 30
Location: Sweden 34 35
Location: Iceland
94 22
Location: Denmark 36 20

Note that a Location is always preceded by "Location:" and that the name and coordinates can be seperated by any number of lines.

I have come up with the following code but it does not seem to be working:

FileInputStream fileIn = new FileInputStream("src\\graph.txt");
Scanner scan = new Scanner(fileIn);
WorldMap map1= new WorldMap();
while(scan.hasNext()) {
    if(scan.next().equals("Location:")) {
        map1.addLocation(scan.next(), scan.nextInt(), scan.nextInt());
    }
}

Upvotes: 0

Views: 51

Answers (2)

RDM
RDM

Reputation: 5066

Better is to read all lines and use a set of regexes to determine what to do with the line.

Upvotes: 0

Neeraj Jain
Neeraj Jain

Reputation: 7730

Replace your code with this :

while(scan.hasNextLine()) {
    if(scan.nextLine().startsWith("Location:")) {
        //doWhatver you want to Do here 
    }
}

Upvotes: 1

Related Questions