2013-07-08 38 views
-8
 public void WeatherInfo(){ 
    ....... 
    String weatherLocation = weatherLoc[1].toString(); 
........ 
} 

基本上我有这个充满活力的字符串,它是在一个名为WeatherInfo无效。如何从另一个void方法访问void方法中的字符串?

但我需要从另一个空白得到weatherLocation字符串,这样

public void WeatherChecker(){ 

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

因此,我需要能够从这一空白访问weatherLocation。

我该怎么做?

+6

调用它们的方法,而不是空洞。 Void只是方法的返回类型。 – Grammin

回答

1

你需要把它作为参数传递或创建一个 “全局变量”

IE,你可以做以下任一操作...

public void methodOne(String string){ 
    System.out.println(string); 
} 
public void methodTwo(){ 
    String string = "This string will be printed by methodOne"; 
    methodOne(string); 
} 

OR(更好的解决方案)

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

public class ThisIsAClass { 

String string; //accessible globally 
.... 
//way down the class 

    public void methodOne(){ 
     System.out.println(string); 
    } 
    public void methodTwo(){ 
     String string = "This string will be printed by methodOne"; //edit the string here 
     methodOne(); 
    } 

让我KN如果您有任何疑问,请联系。当然,您必须相应地更改String string;,但它与任何变量都是相同的概念。

你说你的“句子”是在这些方法之一中创建的,并且它在全局声明时并未创建。您只需在全球范围内创建它即可,然后在需要时进行设置。我认为它你的榜样将是下weatherInfo()

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

而不是创造一个新的,我们只需编辑我们在全球建立的一个。

-Henry

0

我不是100%肯定你想什么来完成,或者哪些功能调用什么其他功能...但你可以只通过weatherLocation作为一个参数。这是你想要的?

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

可以执行以下任何

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

2)使用一个成员变量和使用的吸气剂,以获得变量

+8

和3)遵循java代码约定:) – nachokk

4

这是一个scope的问题。你已经声明了一个本地变量,所以它只能在本地访问。如果您希望在方法之外访问变量,请传递参考或全局声明

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


String str2 = "hello there"; 
// str2 is accessible anywhere in the class. 

编辑

正如指出的那样,你应该看看Java naming Conventions

+2

给出一个示例和+1和一个链接遵循java代码约定 – nachokk

+0

问题是,天气位置是从整个句子中获取,无论何时用户说话并在通话后按下某个按钮。就像,如果句子是“纽约市的天气如何”,按钮的方法会清除不必要的单词,并将weatherLocation设置为NYC。如果我在按钮的onclick方法之外声明weatherLocation,它将不起作用,因为首先不会有句子可用。 –

+0

小心点。 * declare *和* define *之间有区别。你可以在方法外部声明变量,但是只有在方法中已经定义了*之后才能使用它。你可以在第二个方法中包含一个检查,如:if(weatherLocation == null)return;'。 – christopher

0

你不能直接这样做,因为在方法的局部变量只能从它们的声明存在块(这是法的最迟结束)结束。

如果你需要一个以上的方法来访问一个变量,你可以使它成为一个类变量(或领域)。一旦为字段赋值,它将被保存为对象的状态,并且可以在以后随时访问和修改。这当然意味着你必须先设置它。

0

也许尝试在声明字符串在你试图使用它的方法的范围上涨。你必须确保WeatherInfo()被首先调用(可能在构造函数中),以便它被初始化,否则你会得到奇怪的结果。

public Class { 
String weatherLocation = null; 

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