gpt4 book ai didi

java - 如何在其他方法中使用方法中产生的变量?

转载 作者:行者123 更新时间:2023-11-30 06:21:40 25 4
gpt4 key购买 nike

基本上,我需要在另一个方法中或在主 void 运行中使用此方法 spacesCount 中的 spaces 的值。但是它不让我在外面使用?

感谢您的帮助,对不起这里的新程序员。

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 的值作为该方法的返回值。所以你需要将结果存储在一个变量中并在你的其他方法中使用它:

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

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

关于java - 如何在其他方法中使用方法中产生的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20152517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com