本文介绍了菜鸟初始化问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,这在Java上运行良好:

For some reason this runs fine on Java:

public int intMax(int a, int b, int c) {
  int max;
  if (a > b) {
    max = a;
  } else {
    max = b;
  }
  if (c > max) {
    max = c;
  }
  return max;
}



但是当我尝试运行以下内容时,我收到错误变量输出可能尚未初始化:


However when I try to run the following I get the error "variable output might not have been initialized":

public int close10(int a, int b) {
  int output;
  if (Math.abs(a - 10) > Math.abs(b - 10)) {
    output = b;
  }
  if (Math.abs(a - 10) < Math.abs(b - 10)) {
    output = a;
  }
  if (Math.abs(a - 10) == Math.abs(b - 10)) {
    output = 0;
  }
  return output;
}



在第一个示例中,int max未初始化,但是,对于第二个示例,int output必须初始化。我初始化它并给它一个随机数(1)它工作正常,但为什么我必须初始化它而不是另一个?



提前致谢



我尝试了什么:



这里有一点代码,有点代码那里


In the first example "int max" was not initialized, however, for the second one "int output" had to be initialized. I initialized it and gave it a random number (1) and it worked fine but why did I have to initialize it and not the other one?

Thanks in advance

What I have tried:

A little code here, a little code there

推荐答案


Quote:

但是当我尝试运行以下内容时,我收到错误变量输出可能尚未初始化:

However when I try to run the following I get the error "variable output might not have been initialized":



这是因为这段代码超出了编译器的理解。

编译器看到3个独立的条件,但是无法理解它们是互补的,1会做。

因为3条件是互补的,第三个是矫枉过正,并且可以通过以下方式实现相同的逻辑结果:


This is because this code is beyond the compiler understanding.
The compiler see 3 independent conditions but is unable to understand that they are complementary and 1 will do.
Because the 3 conditions are complementary, the third is overkill and the same logical result can be achieved with:

public int close10(int a, int b) {
  int output;
  if (Math.abs(a - 10) > Math.abs(b - 10)) {
    output = b;
  }
  else if (Math.abs(a - 10) < Math.abs(b - 10)) {
    output = a;
  }
  else {
    output = 0;
  }
  return output;
}


这篇关于菜鸟初始化问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:24