英文:
Can anyone explain what's happening in below for loop?
问题
预期输出是
4个顶点,4条边
0: 0 1 0 1
1: 1 0 1 0
2: 0 1 0 1
3: 1 0 1 0
它能够正常工作,没有任何问题,但我不知道在以下toString()方法语句的*第二个for循环内部发生了什么。
有人可以解释一下这个方法内部特别是for循环中发生了什么吗?
另外,为什么这个程序使用StringBuilder而不是String数据类型。
英文:
My expected output is
4 vertices, 4 edges
0: 0 1 0 1
1: 1 0 1 0
2: 0 1 0 1
3: 1 0 1 0
And it works fine without any problem but I don't know what's happening inside the second for loop in the following toString() method statement.
can anyone say what is going on inside this method especially in for loop??
And also why this program uses StringBuilder instead of String data type.
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(V + " vertices, " + E + " edges " + "\n");
for(int v = 0; v < V; v++) {
sb.append(v + ": ");
for(int w : adjMatrix[v]) {
sb.append(w + " ");
}
sb.append("\n");
}
return sb.toString();
}
Here is my full graph program.
public class Graph {
private int V; // number of vertices in Graph
private int E; // number of edges in Graph
private int[][] adjMatrix;
public Graph(int nodes) {
this.V = nodes;
this.E = 0;
this.adjMatrix = new int[nodes][nodes];
}
public void addEdge(int u, int v) {
adjMatrix[u][v] = 1;
adjMatrix[v][u] = 1; // because it is an undirected graph
E++;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(V + " vertices, " + E + " edges " + "\n");
for(int v = 0; v < V; v++) {
sb.append(v + ": ");
for(int w : adjMatrix[v]) {
sb.append(w + " ");
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 0);
System.out.println(g.toString());
}
}
答案1
得分: 0
对于二维数组adjMatrix中的每个整数,您将其值附加到StringBuilder中(实际上只是连接字符串)。
英文:
For every Integer in two-dimensional array adjMatrix, you are appending it's value in StringBuilder (actually just connecting strings).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论