Java 如何从另一个void方法访问void方法中的字符串?

Java 如何从另一个void方法访问void方法中的字符串?,java,android,Java,Android,基本上,我有一个动态字符串,它位于一个名为WeatherInfo的空白处 但我需要从另一个空间中获取weatherLocation字符串,就像这样 public void WeatherInfo(){ ....... String weatherLocation = weatherLoc[1].toString(); ........ } 因此,我需要能够从这个空间访问weatherLocation 我如何做到这一点?我不能100%确定您想要完成什么,或者哪些函

基本上,我有一个动态字符串,它位于一个名为WeatherInfo的空白处

但我需要从另一个空间中获取weatherLocation字符串,就像这样

        public void WeatherInfo(){
    .......
    String weatherLocation = weatherLoc[1].toString();
........
}
因此,我需要能够从这个空间访问weatherLocation


我如何做到这一点?

我不能100%确定您想要完成什么,或者哪些函数正在调用哪些其他函数。。。但是您可以将
weatherLocation
作为参数传入。这就是你要找的吗

    public void WeatherChecker(){

    YahooWeatherUtils yahooWeatherUtils = YahooWeatherUtils.getInstance();
  yahooWeatherUtils.queryYahooWeather(getApplicationContext(), weatherLocation, this);
}

您可以执行以下任一操作

1) 将字符串作为参数传递并设置值

2) 使用成员变量并使用getter获取变量这是一个问题。您已经声明了一个局部变量,因此只能在局部访问它。如果希望在方法之外访问变量,请传递引用或全局声明它

public void WeatherChecker(String weatherLocation){
  YahooWeatherUtils yahooWeatherUtils = YahooWeatherUtils.getInstance();
  yahooWeatherUtils.queryYahooWeather(getApplicationContext(), weatherLocation, this);
}
编辑


正如所指出的,您应该看看。

您不能直接这样做,因为方法中的局部变量只存在于从它们的声明到块的结尾(最晚是方法的结尾)的过程中


如果需要在多个方法中访问变量,可以将其设置为类变量(或字段)。将值指定给字段后,它将保存为对象的状态,并可在以后的任何时间访问和修改。这当然意味着您必须首先设置它。

您需要将其作为参数传递或创建“全局变量”

你可以做以下任何一项

public void method1()
{
   String str = "Hello";
   // str is only accessible inside method1 
}


String str2 = "hello there"; 
// str2 is accessible anywhere in the class.
或者(更好的解决方案)

在类声明下创建一个全局变量

public void methodOne(String string){
    System.out.println(string);
}
public void methodTwo(){
    String string = "This string will be printed by methodOne";
    methodOne(string);
}
如果你有任何问题,请告诉我。当然,您必须更改
字符串相应地,但它与任何变量都是相同的概念

你说你的“句子”是用这些方法中的一种创建的,而当你全局声明它时,它还没有被创建。您只需全局创建它,
String weatherLocation=null
然后在需要时设置它。我认为这是您的示例,它将位于
weatherInfo()下

我们不需要创建一个新的,只需要编辑我们全局创建的


-Henry

也许可以尝试在您尝试使用的方法的范围内将字符串声明得更高一些。您必须确保首先调用了WeatherInfo()(可能在构造函数中),以便对其进行初始化,否则会得到奇怪的结果

public void WeatherInfo(){
    weatherLocation = weatherLoc[1].toString();
}

和3)遵循java代码约定:)给出一个示例和+1以及一个链接来遵循java代码约定问题是,每当用户说话并在说话后按下某个按钮时,天气位置都会从整个句子中提取出来。比如,如果句子是“纽约的天气怎么样”,按钮的方法会清除不必要的单词,并将weatherLocation设置为NYC。如果我在按钮的onclick方法之外声明weatherLocation,它将不起作用,因为一开始就没有可以使用的句子。小心。declare和define之间有区别。您可以在方法外部声明变量,但只有在方法内部定义变量后才能使用它。您可以在第二个方法中包含一个检查,类似于:
if(weatherLocation==null)return。称它们为方法,而不是空洞。Void只是方法的返回类型。
public void WeatherInfo(){
    weatherLocation = weatherLoc[1].toString();
}
public Class {
String weatherLocation = null;

public void WeatherInfo(){
    ........
    weatherLocation = weatherLoc[1].toString();
    ........
}
public void WeatherChecker(){
    YahooWeatherUtils yahooWeatherUtils = YahooWeatherUtils.getInstance();
    yahooWeatherUtils.queryYahooWeather(getApplicationContext(), weatherLocation, this);    
}
}