给定:
11. public static void test(String str) {
12. int check = 4;
13. if (check = str.length()) {
14. System.out.print(str.charAt(check -= 1) +", ");
15. } else {
16. System.out.print(str.charAt(0) + ", ");
17. }
18. }
and the invocation:
21. test("four");
22. test("tee");
23. test("to");
结果是什么?
A. r, t, t,
B. r, e, o,
C. Compilation fails.
D. An exception is thrown at runtime.
Answer: C
能解释一下编译失败的原因吗?
最佳答案
if (check = str.length())
上面的if
中的表达式是一个赋值,它相当于:-
if (str.length())
因此,表达式被计算为整数
值。
这是一个编译错误。由于 if
语句中的表达式应计算为 Java
中的 boolean
值。
因此,if
语句应写为: -
if (check == str.length())
才能成功编译。
关于java - 编译错误相关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13630819/