我创建了一个带有数组属性的类。我还创建了一个对象数组。我想知道如何调用特定对象的数组元素?
课程是:
public class node
{
public int node_num;
public int total_weight;
public int[] neighbors;
node(int num, int weight,int neigh[])
{
this.node_num = num; //node number
this.total_weight = weight; //row total
this.neighbors=neigh; //adjacent nodes
}
}
我的主要功能是:
public static void main(String[] args)
{
int n=5;
int temp1,temp2;
int adj_mat[][]= {{0,4,0,0,10},{4,0,6,2,0},{0,6,0,4,0},{0,2,4,0,0},{10,0,0,0,0}}; //populating the weighted adjacency matrix
int i=0, j=0;
int n1[]=new int[n];
cluster cluster1=new cluster();
node nodes[] = new node[n];
for (i = 0; i < n; i++)
{
int sum=0,k=0;
for (j = 0; j < n; j++)
{
if(adj_mat[i][j]!=0)
{
sum= sum+adj_mat[i][j];
n1[k]=j+1;
k=k+1;
}
else
{
n1[k]=0;
k=k+1;
}
}
nodes[i]=cluster1.new node(i+1,sum,n1);
}
int m;
for(i=0;i<n;i++)
{
System.out.print("\nNeighbor of "+nodes[i].node_num +" is ");
for(m=0;m<5;m++)
{
System.out.print(nodes[i].neighbors[m]+",");
}
}
预期输出为:
1的邻居是0,2,0,0,5,
2的邻居是1,0,3,4,0,
3的邻居是0,2,0,4,0,
4的邻居是0,2,3,0,0,
5的邻居是1,0,0,0,0,
当前输出为:
1的邻居是1,0,0,0,0,
2的邻居是1,0,0,0,0,
3的邻居是1,0,0,0,0,
4的邻居是1,0,0,0,0,
5的邻居是1,0,0,0,0,
答案 0 :(得分:-1)
public class node
{
public int node_num;
public int[] neighbors;
node(int num, int neigh[])
{
this.node_num = num;
this.neighbors=neigh;
}
public int getNode_num(){
return node_num;
}
public int[] getNeighbors(){
return neighbors;
}
}
node nodes[] = new node[n];
for(i=0;i<nodes.length();i++)
{
for(m=0;m<nodes[i].getNeighbors().length();m++)
{
System.out.print(neighbors[m]+",");
}
}