Java 从其他类访问 Main 方法中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20179648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing variable in Main method from other class
提问by Gaurav K.
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?
我想访问int n
的Main
方法和价值分配给private int n
在AdjacencyList
类。我node.n
在一种方法中尝试了(class.variable) 格式,我可以在其中分配值但它不起作用。有人可以帮我解决这个问题吗?
采纳答案by Melquiades
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 hereand here.
回答by subash
change to
改成
public static int n;
then you can access anywhere like this..
那么你可以像这样访问任何地方..
AdjacencyList.n
回答by igr
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
希望能帮助到你
回答by Dave Hulse
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.
您可以这样做,也可以创建 AdjacencyList 的新实例并在构造函数中设置 n。然后使用 get() 函数访问 n。
回答by quez
Add to the second class public setter for n, then create an instance of AjacencyList in main and call the setter.
为n添加第二个类public setter,然后在main中创建一个AjacencyList的实例并调用setter。