Sample Program Using a Graph

import java.util.Scanner;

public class UseGraph {
	public static void main(String[] args) {
		WeightedGraph g = new WeightedGraph();
		String name;
		String from,to;
		int weight;
		Scanner keybd = new Scanner(System.in);

		System.out.println("Enter node names (enter q when finished):");
		name = keybd.next();
		while (!name.equals("q")) {
			g.addVertex(name);
			name = keybd.next();
		}

		System.out.println("Enter edges (enter q when finished):");
		from = keybd.next();
		while (!from.equals("q")) {
			to = keybd.next();
			weight = keybd.nextInt();
			g.addEdge(from,to, weight);
			from = keybd.next();
		}

		g.printGraph();
	}
}

Input File

1
2
3
4
5
6
7
8
9
q
1 2 10
1 3 20
2 4 5
3 5 30
7 5 22
3 6 15
3 7 25
9 5 15
7 2 44
4 8 30
7 9 5
6 9 40
2 8 10
5 7 50
9 1 33
q

Sample Output

C:\Users\Emmi\Documents\My Programs\java\csc236\Dale>java UseGraph < graph.dat
Enter node names (enter q when finished):
Enter edges (enter q when finished):


Vertex: 1
   Edges:
      (1,2) weight: 10
      (1,3) weight: 20
Vertex: 2
   Edges:
      (2,4) weight: 5
      (2,8) weight: 10
Vertex: 3
   Edges:
      (3,5) weight: 30
      (3,6) weight: 15
      (3,7) weight: 25
Vertex: 4
   Edges:
      (4,8) weight: 30
Vertex: 5
   Edges:
      (5,7) weight: 50
Vertex: 6
   Edges:
      (6,9) weight: 40
Vertex: 7
   Edges:
      (7,2) weight: 44
      (7,5) weight: 22
      (7,9) weight: 5
Vertex: 8
   Edges:
Vertex: 9
   Edges:
      (9,1) weight: 33
      (9,5) weight: 15



Email Me | Office Hours | My Home Page | Department Home | MCC Home Page



© Copyright Emmi Schatz 2012