[英]Accessing variable in Main method from other class
我有两节课:
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;
我想从Main
方法访问int n
并将其值分配给AdjacencyList
类中的private int n
。 我在一种可以分配值但无法解决的方法中尝试了node.n
(class.variable)格式。 有人可以帮我吗?
改成
public static int n;
那么您可以在任何地方访问此类内容。
AdjacencyList.n
只是,
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();
你不能 局部变量(在函数内部定义的变量)的作用域仅限于此函数(此处为Main,请注意:实践中以小写字母开头的函数名是惯例)。
如果要从外部访问某些变量,则该变量必须是类变量,并且声明要访问它的函数(setN / getN或类似名称...)
另外,由于函数是静态的,所以变量也必须是静态的。
希望能帮助到你
您可以执行此操作,也可以创建AdjacencyList的新实例并在构造函数中设置n。 然后使用get()函数访问n。
将n添加到第二个类的公共setter中,然后在main中创建AjacencyList的实例并调用setter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.