“变量可能尚未初始化” [英] "Variable may not have been initialized"

查看:185
本文介绍了“变量可能尚未初始化”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建 String 的方法和另一个更改字符串的方法

I've got a method that creates a String and another method that changes Strings

void create(){
    String s;
    edit(s);
    System.out.println(s);
}

void edit(String str){
    str = "hallo";
}

我的编译器说它可能尚未初始化。

My compiler says that it "may not have been initialized".

有人可以解释一下吗?

推荐答案


变量可能尚未初始化

Variable may not have been initialized

当你在一个方法中定义 s 时你必须初始化 s ,程序中的每个变量在使用它之前必须有一个值。

As you define the s inside a method you have to init s in it somewhere every variable in a program must have a value before its value is used.

另外一件事情并不那么重要,你的代码永远不会像预期的那样工作因为
java中的字符串是不可改变的,那么你就无法编辑你的字符串,所以你应该改变你的方法 edit(Str s)

Another thing not less important, your code won't never work as you expected cause Strings in java are inmutable then you cannot edit your String, so you should change your method edit(Str s).

我将你的代码更改为类似的东西,但我认为你的编辑方法应该做另一件事,而不是返回hallo。

I Change your code to something like this but i think your edit method should do another thing rather than return "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是传递参考吗?

Read more about that java is passed by value in this famous question : Is Java "pass-by-reference"?

请参阅这个简单的示例,显示java是按值传递的。我不能只用字符串做一个例子,因为字符串是不可改变的。所以我创建了一个包含String的包装类,该String可以看到差异。

See this simple Example showing that java is passed by value. I cannot make an example with only Strings cause Strings are inmutable. So i create a wrapper class containing a String that is mutable to see differences.

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
    a.s = "bye-bye";
}

public static void modifyValue(A a){
   a.s ="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 
}


}

这篇关于“变量可能尚未初始化”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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