- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
int anInt = 1;
double aDouble = 2.5;
anInt = anInt + aDouble; // Error - need to cast double to int
anInt += aDouble; // This is ok. Why?
anInt = aDouble; // This is also an error.
anInt = 1 + aDouble; // This is also an error.
所以我的问题是:为什么执行 anInt += aDouble
不是编译错误?
最佳答案
四种情况中的三种正确报告错误。复合赋值是该规则的唯一异常(exception)。 Java 语言规范第 15.26.2 部分解释了原因:
15.26.2 Compound Assignment Operators
A compound assignment expression of the form
E1 op= E2
is equivalent toE1
, where
= (T) ((E1) op (E2))T
is the type ofE1
, except thatE1
is evaluated only once.For example, the following code is correct:
short x = 3;
x += 4.6;and results in x having the value 7 because it is equivalent to:
short x = 3;
x = (short)(x + 4.6);
如您所见,通过隐式插入强制转换避免了错误。
关于Java Puzzler - 将 double 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28833590/
abstract class AbstractBase { abstract void print(); AbstractBase() { // Note that t
这个问题不太可能帮助任何 future 的访问者;它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况有关,这些情况并不普遍适用于互联网的全局受众。为了帮助使这个问题更广泛地适用,visit
我一直在反对这个问题一段时间,并认为也许一些新的眼睛会看到这个问题;感谢您的宝贵时间。 import java.util.*; class Tbin extends ArrayList {} clas
此代码涉及递归存储过程调用和避免游标名称冲突的“不太好”的方法。最后我不在乎它是否使用游标。只是在寻找最优雅的方法。我主要将它用作跟踪存储过程层次结构的简单方法(无需购买产品)。我在“动态 sql”中
在新的第三版 Effective Java 中,Joshua Bloch 提到了来自 Java Puzzlers 的一段代码(它是关于在 try-finally 中关闭资源): For starter
int anInt = 1; double aDouble = 2.5; anInt = anInt + aDouble; // Error - need to cast double to int
看看这个java puzzles vid作者:Josh Bloch 和 William Pugh,时间索引 0:25:00-0:33:00 左右。 一位发言者说,如果你使用小写的boolean而不是B
我是一名优秀的程序员,十分优秀!