菜鸟初始化问题 [英] Rookie initialization question

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

问题描述

出于某种原因,这在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

推荐答案

问题是:在第一个代码片段中, max 总是被初始化(从编译器的角度来看)因为有一个 else 子句。这个 else 子句确保变量总是被初始化。

没有 else 第二段中的子句。因此,再次从编译器的角度来看,有一个未初始化成为可能(即使数学上,必须满足三个条件之一)。
Problem is: in the first snippet, max is always initialized (from the compiler's point of view) since there is an else clause. This else clause ensures that the variable will always be initialized.
There is no else clause in the second snippet. Thus, again from the compiler's point of view, there is an uninitialization made possible (even if, mathematically, one of the three conditions will necessarily be met).


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;
}


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

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