java - 编译错误相关

标签 java static static-methods

给定:

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/

相关文章:

java - 将 Spinners 的文本发送到邮件

java.lang.VerifyError : Expecting a stackmap frame at branch target 73

java - Spring Security 中奇怪的对象类型更改

java - 静态字段每次使用时都会被调用/加载吗?

java - 静态和非静态方法/子例程之间的区别

java - @Autowired bean 在静态方法中作为 null

php - 是否可以在 PHP 中创建静态类(如在 C# 中)?

c++ - 静态成员与静态常量成员实例化 - 有什么区别?

java - 即使对于无状态类,静态方法在java中总是不被鼓励吗?

c++ - 许多类之间的静态变量初始化顺序