如何在其他方法中使用方法中生成的变量?

use*_*003 2 java

基本上,我需要在另一个方法中使用spacesfrom this方法的值spacesCount,或者在main void run中使用.但它不会让我在外面使用?

谢谢你的帮助,对不起这位新程序员.

public static int spacesCount(String str){
    int spaces = 0;
    for(int i=0; i<str.length(); i++){
       if(str.charAt(i) == ' '){
         spaces++;       
       }
    }
    return spaces;
}
Run Code Online (Sandbox Code Playgroud)

mel*_*okb 5

spaces将从方法中提供值作为返回值.因此,您需要将结果存储在变量中,并在其他方法中使用它:

public static void main(String args[]) {
    String myString = "this is a test";

    int spaces = spacesCount(myString);
    // use spaces to do something
}
Run Code Online (Sandbox Code Playgroud)