user3023003
user3023003

Reputation: 53

How to use a variable produced in a method in other methods?

Basically, i need to use the value of spaces from this method spacesCount in another method, or in the main void run. But it won't let me use outside?

Thanks for your help, sorry new programmer here.

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

Upvotes: 2

Views: 67

Answers (1)

mellamokb
mellamokb

Reputation: 56769

You are providing the value of spaces as the return value from the method. So you need to store the result in a variable and use it in your other method:

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

    int spaces = spacesCount(myString);
    // use spaces to do something
}

Upvotes: 5

Related Questions