Java 如何在另一种方法中调用变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19918414/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:18:07  来源:igfitidea点击:

How to call a variable in another method?

java

提问by Mamen

How to call a variable in another methodin the same class?

如何method在同一个变量中调用另一个变量class

public void example(){    
    String x='name';
}

public void take(){
    /*how to call x variable*/
}

采纳答案by Bohemian

First declare your method to accept a parameter:

首先声明你的方法来接受一个参数:

public void take(String s){
    // 
}

Then pass it:

然后通过它:

public void example(){
    String x = "name";
    take(x);
}


Using an instance variable is not a good choice, because it would require calling some code to set up the value beforetake()is called, and take()have no control over that, which could lead to bugs. Also it wouldn't be threadsafe.

使用实例变量不是一个好的选择,因为它需要在调用之前调用一些代码来设置值take(),并且take()无法控制它,这可能会导致错误。它也不会是线程安全的。

回答by JBarberU

Since they are in different scopes you can't.

因为它们在不同的范围内,所以你不能。

One way to get around this is to make x a member variable like so:

解决这个问题的一种方法是使 xa 成员变量像这样:

String x;

public void example(){
    this.x = "name";
}

public void take(){
    // Do stuff to this.x
}

回答by clcto

You make it an instance variable of the class:

你使它成为类的实例变量:

public class MyClass
{
    String x;

    public void example(){ x = "name"; } // note the double quotes
    public void take(){ System.out.println( x ); }
}

回答by ChiragC

public class Test
{

static String x;
public static void method1
{
x="name";
}

public static void method2
{

System.out.println(+x);

}

}