[英]Add Vertex From Input File Graph Java
I am attempting to implement a graph in Java. 我正在尝试用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: 这是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. 但我有一个错误。
for (z=1;z<7;z++){
graphNew.inserVertex(Alist.get(z));
}
Indices in java are 0 based, not 1 based. Java中的索引基于0,而不是基于1。
That means the first index is 0
, and the last index (you can access) is Alist.length() - 1
, which is 5
in your case. 这意味着第一个索引为
0
,最后一个索引(您可以访问)为Alist.length() - 1
,在您的情况下为5
。
As side notes: 作为旁注:
You should prefer a for each loop over an old style index loop: 与旧式索引循环相比,您应该更喜欢for each循环:
for (String city : Alist) graphNew.inserVertex(city); 对于(String city:Alist)graphNew.inserVertex(city);
variables in java start with lower case letter ( aList
instead of Alist
). Java中的变量以小写字母开头(
aList
而不是Alist
)。 This is not enforced by compiler, but is a convention. 这不是由编译器强制执行的,而是一种约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.