Reputation: 27
I am using Treeset
to sort edges, here's the code:
TreeSet<Edge> edges = new TreeSet<Edge>();
//Sample problem - replace these values with your problem set
edges.add(new Edge("0", "1", 2));
edges.add(new Edge("0", "3", 1));
edges.add(new Edge("1", "2", 3));
edges.add(new Edge("2", "3", 5));
edges.add(new Edge("2", "4", 7));
edges.add(new Edge("3", "4", 6));
edges.add(new Edge("4", "5", 4));
System.out.println("Graph");
KruskalEdges vv = new KruskalEdges();
for (Edge edge : edges) {
System.out.println(edge);
vv.insertEdge(edge);
}
I just want to take inputs from user instead of giving statically into edges.add
Upvotes: 0
Views: 2028
Reputation: 25950
Use a loop to prompt for 3 parameters of each Edge
instance (You can do this via Scanner
class.). Then process these parameters (I mean use String
class functions, etc. ) to construct instances. Finally, add each instance to your edge set in the same loop. Sample code:
TreeSet<Edge> edges = new TreeSet<Edge>();
Scanner scanner = new Scanner(System.in);
int counter = 10;
while (counter > 0)
{
System.out.println("Enter edge parameters:");
String temp = scanner.nextLine();
String[] params = temp.split("-");
edges.add(new Edge(params[0], params[1], Integer.valueOf(params[2])));
counter--;
}
Note: The loop above executes 10-times, it's just for demo, you can manipulate the loop yourself. It expects user to enter dash(-) as separator of the parameters. A valid user input could be like: 24-5-6 And also be careful about error handling, mismatching user inputs are not handled in this code.
Upvotes: 0
Reputation: 15664
If your Edge
constructor takes two String
arguments and one int
argument then simply read two String
and one int
using Scanner, store them in variables and then pass them to the Edge
constructor.
Upvotes: 3
Reputation: 327
You may use scanner to get inputs at runtime
//From command line
Scanner in = new Scanner(System.in);
//From file
Scanner sc = new Scanner(new File("edges"));
while (sc.hasNextLong()) {...}
you'll then have to instantiate Edge objects with these values and use it in your TreeSet
Upvotes: 0
Reputation: 22890
Look at the documentation of Scanner to figure out how to get inputs in a simple way.
Upvotes: 0