“变量可能尚未初始化”
我有一个创建String
方法和另一个更改字符串的方法
void create(){ String s; edit(s); System.out.println(s); } void edit(String str){ str = "hallo"; }
我的编译器说它“可能尚未初始化”。
有人可以解释一下吗?
变量可能尚未初始化
当你在方法中定义s
你必须在某个地方初始化它,程序中的每个变量在使用它之前必须有一个值。
另一件重要的事情是,你的代码永远不会像预期的那样工作,因为java中的字符串是不可变的,那么你就无法编辑你的字符串,所以你应该改变你的方法edit(Str s)
。
我将你的代码更改为这样的东西,但我认为你的编辑方法应该做另一件事,而不是返回“hallo”。
void create(){ String s=null; s =edit(); // passing a string to edit now have no sense System.out.println(s); } // calling edit to this method have no sense anymore String edit(){ return "hallo"; }
阅读更多关于java在这个着名问题中通过值传递的信息: Java是“传递引用”吗?
看到这个简单的示例,显示java是按值传递的。 我不能只用字符串做一个例子,因为字符串是不可改变的。 所以我创建了一个包含String的包装类,该String可以看到差异。
public class Test{ static class A{ String s = "hello"; @Override public String toString(){ return s; } } public static void referenceChange(A a){ a = new A(); // here a is pointing to a new object just like your example as = "bye-bye"; } public static void modifyValue(A a){ as ="bye-bye";// here you are modifying your object cuase this object is modificable not like Strings that you can't modify any property } public static void main(String args[]){ A a = new A(); referenceChange(a); System.out.println(a);//prints hello, so here you realize that a doesn't change cause pass by value!! modifyValue(a); System.out.println(a); // prints bye-bye } }
您在方法create
声明了局部变量s
,因此您需要在使用它之前对其进行初始化。 请记住,java没有局部变量的默认值。 Init String s = ""
或代码将正常运行的任何值。
尝试将字符串“s”初始化为空值,因为您已声明变量“s”但尚未初始化。 因此,当用作参数时,它不能传递该变量的引用。
String s = null;
希望这可以帮助
给你的变量S一个值,或者像Jeroen Vanneve所说的那样“将它改为String s = null;”