user3099626 user3099626 - 1 year ago 64
Java Question

Add Vertex From Input File Graph Java

I am attempting to implement a graph in Java. I want to add vertex from the input file. Here is my code:

Scanner input = new Scanner(;

ArrayList<String> Alist= new ArrayList <String>();
FileReader fr= new FileReader("/home/vanhook/Desktop/city.txt");
BufferedReader reader= new BufferedReader(fr);

String line;
while ((line=reader.readLine()) !=null)
//Add to ArrayList

//print the city
for (int z = 0; z < 7; z++)

Here is the code to add vertex manually
Graph graphNew = new Graph();
graphNew.insertVertex("Jakarta"); //0
graphNew.insertVertex("Bandung"); //1
graphNew.insertVertex("Semarang"); //2
graphNew.insertVertex("Surabaya"); //3
graphNew.insertVertex("Madura"); //4
graphNew.insertVertex("Bali"); //5

Here is the city.txt:


What is the code to replace manually insert vertex with the input file? I try to use looping like this:

for (int z = 1; z < 7; z++)

but I got an error.

Answer Source
for (z=1;z<7;z++){

Indices in java are 0 based, not 1 based.

That means the first index is 0, and the last index (you can access) is Alist.length() - 1, which is 5 in your case.

As side notes:

  1. You should prefer a for each loop over an old style index loop:

    for (String city : Alist) graphNew.inserVertex(city);

  2. variables in java start with lower case letter (aList instead of Alist). This is not enforced by compiler, but is a convention.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download