user3099626 user3099626 - 6 months ago 13
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(System.in);

try
{
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
Alist.add(line);
}

//print the city
for (int z = 0; z < 7; z++)
{
System.out.println(Alist.get(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:

Jakarta
Bandung
Semarang
Surabaya
Madura
Bali


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++)
{
graphNew.inserVertex(Alist.get(z));
}


but I got an error.

Answer
for (z=1;z<7;z++){
graphNew.inserVertex(Alist.get(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.