gpt4 book ai didi

java - 为什么这个方法没有返回值

转载 作者:行者123 更新时间:2023-12-01 09:35:31 24 4
gpt4 key购买 nike

public class Main {

public static void main(String []args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter word: ");
String text = reader.nextLine();
System.out.println(calculateCharacters(tex));
reader.close();
}

public static int calculateCharacters(String text, int tex){
tex = text.length();
return tex;
}
}

因此,我从 String text 接收一个字符串,然后将其发送到方法以计算其长度并返回一个应由 System.out.println(calculateCharacters(tex)); 拦截的数字 并且问题应该显示输入的字符串中的字母数,问题是:没有到达 System.out.println(calculateCharacters(tex)); 为什么?那么返回它的 return tex; 在哪里?

最佳答案

嗯,我不完全确定为什么你有一个 int tex 变量,但删除它可以让这个完美地工作。尝试重写你的方法:

public static int calculateCharacters(String text) {
int tex = text.length();
return tex;
}

或者如果您准备好变得时髦:

public static int calculateCharacters(String text) {
return text.length();
}

Java 是按值传递的 ( Is Java "pass-by-reference" or "pass-by-value"? ),因此在其中保留一个仅用于本地存储内容的额外 int 实际上不会改变 tex 的值。

此外,您还可以实例化 String text,然后将 tex 传递给 calculateCharacters()。由于您在此之前尚未创建 tex 变量,因此编译器不知道要传递给 calculateCharacters() 的内容。尝试将其更改为:

System.out.println(calculateCharacters(text)); 

相反。

关于java - 为什么这个方法没有返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38981609/

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