Java 变量可能尚未初始化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16772394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:58:48  来源:igfitidea点击:

Java variable might not have been initialized?

javavariablesbluejinitialization

提问by ninopino1

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

当我尝试编译类时,我的 BlueJ IDE 显示此错误。我看不出我做错了什么。

enter image description here

在此处输入图片说明

回答by Arthur Dent

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.

如果 if 子句中的条件不为真,则不分配变量。在这种情况下,后面的返回引用了一个未初始化的变量。

回答by EnKrypt

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

在 if 块中使用变量之前,您需要对其进行初始化。

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.

但请记住,如果您的条件返回 false,因为您没有指定 else 块,您的变量将保持为 0。

回答by Rishikesh Dhokare

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.

这是一个私有方法,局部变量没有默认值,它们必须被初始化。考虑这样一种情况,其中控制不会进入 if 块,那么您的变量不包含任何值,因此会出现错误。

回答by NINCOMPOOP

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.

编译器抱怨是因为默认情况下局部变量没有分配任何值。因此,在运行时,如果if()条件失败,则不会为变量分配任何值,在这种情况下,运行时应将什么值返回给函数的调用者?因此用一些默认值初始化它。