Tricky but not hard endless loop exercise

huangapple go评论59阅读模式
英文:

Tricky but not hard endless loop exercise

问题

我在Java测试中看到了这个练习,最终我不得不寻求想法,因为有一些解决方案我尝试过,但显然无法解决问题,这是由于数学条件造成的。

所以这个练习:

定义变量S和T,使得在下面的无限循环中成立!

while (s <= t && s >= t && s != t) {

}
英文:

I saw this exercise on a Java test, which finally led me to ask for ideas because there are some solutions I tried, but obviously won't solve the problem, due to Math conditions.

So the exercise:

> Define S and T variables as it results an endless while loop below!

while(s &lt;= t &amp;&amp; s &gt;= t &amp;&amp; s != t) 
{

}

答案1

得分: 1

思考面向对象编程,实际上 0!=0 是假的,但是 new Integer(0) != new Integer(0) 是真的,因为它们不是同一引用。
因此 Integer S = new Integer(0); Integer T = new Integer(0);
应该能解决你的问题。

英文:

think about OOP, in fact 0!=0 is false, but new Integer(0) != new Integer(0) is true because it's not the same reference.
so Integer S= new Integer(0);
Integer T = new Integer(0);

should resolve your problem

答案2

得分: 1

这是答案:
这在原始类型中是不可能的。您可以使用封装的整数类型实现:

Integer a = new Integer(1);
Integer b = new Integer(1);
<= 和 >= 比较将使用非封装的值 1,而 != 将比较引用并成功,因为它们是不同的对象。
您可以在此链接中查看更多详细信息:https://stackoverflow.com/questions/19042393/how-can-a-b-b-a-a-b-be-true/19042429

英文:

here is answer :
This is not possible with primitive types. You can achieve it with boxed Integers:

Integer a = new Integer(1);
Integer b = new Integer(1);
The <= and >= comparisons will use the unboxed value 1, while the != will compare the references and will succeed since they are different objects.
you can check farther details in this link https://stackoverflow.com/questions/19042393/how-can-a-b-b-a-a-b-be-true/19042429

huangapple
  • 本文由 发表于 2020年9月11日 22:49:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63849431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定