如何在其他方法中使用在一个方法中产生的变量? [英] How to use a variable produced in a method in other methods?

查看:45
本文介绍了如何在其他方法中使用在一个方法中产生的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要在另一种方法或主要的空运行中使用此方法 spacesCount 中的 spaces 的值.但这不会让我在外面使用吗?

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;
}

推荐答案

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

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
}

这篇关于如何在其他方法中使用在一个方法中产生的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆