List<Graph.Edge> list = new ArrayList<Graph.Edge>(); try { Scanner scanner = new Scanner(new File(filepath)); while(scanner.hasNextLine()){ String source = scanner.findInLine(NAME); if (source != null) { while(true) { String to = scanner.findInLine(NAME); if (to == null) { break; } int weight = Integer.valueOf(scanner.findInLine(WEIGHT)); list.add(new Graph.Edge(source, to, weight)); } } scanner.nextLine(); } } catch (Exception e) { e.printStackTrace(); }
private static final Graph.Edge[] GRAPH = getEdges("input.txt"); // <-- CHANGED THIS private static final String START = "1"; // <-- CHANGED THIS private static final String END = "5"; // <-- CHANGED THIS private static Graph.Edge[] getEdges(String fileName) { // <-- ADDED THIS final Pattern NAME = Pattern.compile("\\w+"); final Pattern WEIGHT = Pattern.compile("\\d+"); List<Graph.Edge> list = new ArrayList<>(); try { Scanner scanner = new Scanner(new File(fileName)); while (scanner.hasNextLine()) { String source = scanner.findInLine(NAME); if (source != null) { while (true) { String to = scanner.findInLine(NAME); if (to == null) { break; } int weight = Integer.valueOf(scanner.findInLine(WEIGHT)); list.add(new Graph.Edge(source, to, weight)); } } if (scanner.hasNextLine()) // <-- ADDED THIS scanner.nextLine(); } } catch (FileNotFoundException | NumberFormatException e) { } return list.toArray(new Graph.Edge[0]); // <-- ADDED THIS }
//do not assign value yet private static final Graph.Edge[] GRAPH; ... //static initializer block static{ //get a reference to the array you are talking about //You can do whatever you like with tempGraph, not necessarily in one line Graph.Edge[] tempGraph = { new Graph.Edge("a", "b", 7), new Graph.Edge("a", "c", 9), new Graph.Edge("a", "f", 14), new Graph.Edge("b", "c", 10), new Graph.Edge("b", "d", 15), }; //you set GRAPH to be the previously built tempGraph //this is what you can do only one time, only in static initalizer block GRAPH = tempGraph; }
private static final Graph.Edge[] GRAPH = { new Graph.Edge("a", "b", 7), new Graph.Edge("a", "c", 9), new Graph.Edge("a", "f", 14), new Graph.Edge("b", "c", 10), new Graph.Edge("b", "d", 15), new Graph.Edge("c", "d", 11), new Graph.Edge("c", "f", 2), new Graph.Edge("d", "e", 6), new Graph.Edge("e", "f", 9), };
/** * @throws CycleException * @see Graph#topologicalSort() */ @Test(expected = CycleException.class) public void topologicalSort_shouldThrowCycleException() throws CycleException { Graph<String> graph = new Graph<>(); graph.addNode("E"); graph.addNode("D"); graph.addNode("C"); graph.addNode("B"); graph.addNode("A"); graph.addEdge(graph.new Edge( "A", "B")); graph.addEdge(graph.new Edge( "A", "C")); graph.addEdge(graph.new Edge( "B", "C")); graph.addEdge(graph.new Edge( "B", "D")); graph.addEdge(graph.new Edge( "D", "A")); graph.topologicalSort(); }