1

我有两节课:

public class node {
  static LinkedList<Integer> nodes = new LinkedList<Integer>();
  public boolean visited;

  public static void Main (String args []) {
    System.out.println("Number of nodes in network");
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();

    for (int i=1;i<=n;i++){
      nodes.add(i);
    }

    System.out.println(nodes);
  }

和另一个班级

public class AdjacencyList {
  private int n;
  private int density;

我想int nMain方法访问并将其值分配给private int nAdjacencyList。我尝试node.n了(class.variable)格式,我可以在其中分配值但它不起作用。有人可以帮我吗?

4

5 回答 5

7

改成

public static int n;

然后你可以像这样访问任何地方..

AdjacencyList.n
于 2013-11-24T19:14:40.833 回答
3

简单地,

public class AdjacencyList {
    private int n;
    private int density;

    //method to get value of n
    public int getN() { return this.n; }

    //method to set n to new value
    public void setN(final int n) { this.n = n; }

然后,在你的 main() 中,你可以这样做:

AdjacencyList myList = new AdjacencyList();

//set n to any value, here 10
myList.setN(10);

//get n's current value
int currentN = myList.getN();

所有这些都是基本的 java 东西,请再次阅读文档,尤其是herehere

于 2013-11-24T20:00:38.980 回答
0

你不能。局部变量(在函数内部定义的变量)的作用域仅限于此函数(此处为 Main,注意:习惯上以小写字符开头的函数名称)。

如果你想从外部访问某个变量,它需要是类变量并且你声明函数来访问它( setN / getN 或类似的......)

此外,由于函数是静态的,因此变量也需要是静态的。

希望能帮助到你

于 2013-11-24T19:15:48.840 回答
0

您可以这样做,也可以创建 AdjacencyList 的新实例并在构造函数中设置 n 。然后使用 get() 函数访问 n。

于 2013-11-24T19:17:33.233 回答
0

将 n 添加到第二类公共 setter,然后在 main 中创建 AjacencyList 的实例并调用 setter。

于 2013-11-24T19:24:06.013 回答