Java variable might not have been initialized? [closed]

谁说胖子不能爱 提交于 2019-12-02 17:52:36

问题


My BlueJ IDE is showing this error when I try to compile the class. I can't see what I'm doing wrong.


回答1:


Before you can use a variable inside your if block , you need to initialize it.

Try this :

double albedo=0;

Instead of :

double albedo;

Keep in mind though that your variable will remain 0 if your condition returns false as you haven't specified an else block.




回答2:


If the condition in the if clause is not true, the variable is not assigned. In this case, the return that follows references an uninitialized variable.




回答3:


This is a private method and local variables don't get default values, they have to be initialized. Consider a case where control doesn't go inside if block, then your variable contains no value, hence the error.




回答4:


Local variables should be initialized with value before using it .Something like this :

  double albedo = 0.0;

The compiler complains because local variables are not assigned any value by default. So at run time if the if() condition fails then the variable will not be assigned any value and in that case what value should the run time return back to the caller of the function ? Hence initialize it with some default value.



来源:https://stackoverflow.com/questions/16772394/java-variable-might-not-have-been-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!