简体   繁体   English

从其他类访问Main方法中的变量

[英]Accessing variable in Main method from other class

I have two classes: 我有两节课:

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);
  }

and another class 和另一类

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

I want to access int n from Main method and assign its value to private int n in AdjacencyList class. 我想从Main方法访问int n并将其值分配给AdjacencyList类中的private int n I tried node.n (class.variable) format in a method where I can assign values but its not working out. 我在一种可以分配值但无法解决的方法中尝试了node.n (class.variable)格式。 Can anybody please help me with this? 有人可以帮我吗?

change to 改成

public static int n;

then you can access anywhere like this.. 那么您可以在任何地方访问此类内容。

AdjacencyList.n

Simply, 只是,

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; }

Then, in your main(), you can do this: 然后,在您的main()中,您可以执行以下操作:

AdjacencyList myList = new AdjacencyList();

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

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

All this is basic java stuff, please go through the docs again, especially here and here . 所有这些都是基本的Java东西,请再次浏览文档,尤其是在这里这里

You can't. 你不能 Local variables (variables defined inside functions) have scope limited to this function (here Main, note: it is practice to start with lowercase character for function names). 局部变量(在函数内部定义的变量)的作用域仅限于此函数(此处为Main,请注意:实践中以小写字母开头的函数名是惯例)。

If you want some variable to be accessed from outside, it needs to be class variable and that you declare functions to access it ( setN / getN or similar...) 如果要从外部访问某些变量,则该变量必须是类变量,并且声明要访问它的函数(setN / getN或类似名称...)

Also, as function is static, variable also needs to be static. 另外,由于函数是静态的,所以变量也必须是静态的。

Hope it helps 希望能帮助到你

You can do that or you can create a new instance of AdjacencyList and set n in the constructor. 您可以执行此操作,也可以创建AdjacencyList的新实例并在构造函数中设置n。 Then access n with a get() function. 然后使用get()函数访问n。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM