简体   繁体   中英

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. I tried node.n (class.variable) format in a method where I can assign values but its not working out. 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:

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 .

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).

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...)

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. Then access n with a get() function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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