Java:局部变量已初始化,仍然出现错误 [英] Java: Local variable is initialized, still get an error

查看:77
本文介绍了Java:局部变量已初始化,仍然出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此代码上没有发现任何错误,但是eclipse告诉我变量未初始化.这只是一个警告,但编译后也不起作用.我根本找不到错误,而且此代码是100%正确的.请注意,此代码的结构不易更改,因为下面提供的代码已简化,因此您无需阅读太多;-)

I don't spot any mistake on this code, however eclipse tells me that the variables are not initialized. It is only a warning, but after compiling it doesn't work either. I simply can't find the mistake and thing of this code being 100% correct. Please note that the structure of this code can not easily be changed because the code provided below is simplified so you do not have that much to read ;-)

int min1; float somefloat;
try {
    //setting values for min and somefloat
    min1 = 1;
    somefloat = 0.92f;
} catch (IOException ioe) {
    System.err.println("Read Exception");
} 
while (true){
    //warning: variables min1 and somefloat may not be initialized.
    float value1 = (1023 - min1) * somefloat;
    System.out.println("Value: " + value1);
}

推荐答案

编译器不会分析在特定情况下是否会初始化变量或否.它可以确保如果仅在 try 中而不是在 catch finally 中初始化变量,则将确保它们可能 >未初始化.

Compiler doesn't analyse if in concrete case the variables would be initialized or no. It assures that if the variables are initialized only in try, and not in catch or finally it would assure they may be not initialized.

在明显"条件(例如if(1>0) {})下进行类似的尝试.编译器将编译而不分析您的代码.虽然对于人类来说,很明显会发生某些事情,但是Java编译器没有代码可以检测到这种情况,而且Java语法也没有指定代码.因此,您期望编译器提供它所没有的AI,以保持编译清晰,可预测和快速.

Give a similar try with "obvious" condition like if(1>0) {}. The compiler compiles and not makes the analysis of your code. While for human it is obvious that something will happen, the java compiler have no code to detect such cases, neither it is specified by java syntax. So you're expecting from the compiler the AI it doesn't have, to keep the compiling clear, predictable and fast.

您的代码会顺便说一句错误,而不是您描述的错误,因为没有地方可以抛出IOException.

Your code has, BTW, error that will be reported instead of this you describe, because there's no place IOException can be thrown.

这篇关于Java:局部变量已初始化,仍然出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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