Skip to content
Advertisement

How to read a file into a weighted digraph

I want to implement a weighted digraph for my Assignment. I already have the code (it’s a lot of code, so I can’t post it here), but I want to load the text file into the graph and I’m having a hard time. My problem ist that the file has two Strings and one integer Data. Do you have any suggestions? The file is:

  • Home, Drugstore, 12
  • Home, Butcher, 6
  • Home, Lidl, 5
  • Drugstore, Home, 12
  • Drugstore, Bakery, 4
  • Butcher, Home, 6
  • Butcher, Drugstore, 8
  • Butcher, Bakery, 7
  • Lidl, Butcher, 4
  • Aldi, Drugstore, 9
  • Aldi, Bakery, 8
  • Bakery, Pharmacy, 2
  • Bakery, Edeka, 15
  • Edeka, Bakery, 15
  • Edeka, Aldi, 6
  • Edeka, Pizzeria, 5
  • Pizzeria, Bakery, 8
  • Pizzeria, Pharmacy, 9
  • Pharmacy, Pizzeria, 9
  • Pharmacy, Lidl, 6
  • Lidl, Pharmacy, 6
public static void main(String[] args) throws Exception{
    File filePath = new File("C:\Users\F\Desktop\A9\small_town.txt");
    FileReader fr = new FileReader(filePath);
    BufferedReader br = new BufferedReader(fr);

    WeightedDigraph graph = new WeightedDigraph();
    String line;

    while ((line = br.readLine()) != null) {
        String[] nodes = line.split(",");
        if (nodes.length == 3){
            graph.add(nodes[0], nodes[1], Integer.parseInt(nodes[2]));
        }
    }
    System.out.println("The graph:n" + graph);
}

Advertisement

Answer

Currently you are getting a NumberFormatException when parsing the split String to int. The main culprit that causes this is the whitespace inside of your String.

If you look at a line of your input

Home, Drugstore, 12
     ^          ^

you have whitespaces at the marked locations. These whitespaces are still part of the split strings after you do line.split(",") (whitespaces shown as underscores):

Home
_Drugstore
_12

And since your input to Integer.parseInt() then contains a whitespace, you get the aforementioned exception.

The solution:

a) Remove whitespaces completely when split()ting:

line.split("\s*,\s*")

Since split() takes a regular expression as the input, you can provide one which splits on the comma including all whitespaces. (I would suggest this solution, since you don’t really want these whitespaces in any of your Strings after splitting)

b) Optional – Only trim the relevant string:

graph.add(nodes[0], nodes[1], Integer.parseInt(nodes[2].trim()));

String#trim() removes with any leading and trailing whitespaces.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement