【问题标题】:Why the compilation error for boolean and String为什么布尔值和字符串的编译错误
【发布时间】:2013-05-10 12:14:21
【问题描述】:

我有以下代码

public class Test {
  public static void main(String[] args) {
    Integer i1=null;

    String s1=null;
    String s2=String.valueOf(i1);
    System.out.println(s1==null+" "+s2==null);//Compilation Error
    System.out.println(s1==null+" ");//No compilation Error
    System.out.println(s2==null+" ");//No compilation error
  }
}

为什么将两个布尔值与字符串结合会出现编译错误

编辑:编译错误是 运算符 == 未定义参数类型 boolean, null

【问题讨论】:

  • 以后,如果你要发布不能编译的代码并询问编译错误的原因,请包含错误
  • 对不起,我添加了编译错误

标签: java string boolean


【解决方案1】:

这是一个优先级的问题。我永远记不起所有的优先规则(我也不会尝试),但我怀疑编译器试图将其解释为:

System.out.println((s1==(null+" "+s2))==null);

...这没有意义。

不清楚你期望这三行中的任何一行要做什么,但你应该使用括号让编译器和读者都清楚你的意图。例如:

System.out.println((s1 == null) + " " + (s2==null));
System.out.println((s1 == null) + " ");
System.out.println((s2 == null) + " ");

或者您可以使用局部变量使其更清晰:

boolean s1IsNull = s1 == null;
boolena s2IsNull = s2 == null;

System.out.println(s1IsNull + " " + s2IsNull);
System.out.println(s1IsNull + " ");
System.out.println(s2IsNull + " ");

【讨论】:

  • 请参阅bmanolov.free.fr/javaoperators.php 以了解先处理哪个运算符。
  • @mszalbach:我通常的经验法则是,如果从代码中不明显,我应该向其他读者澄清。我非常刻意没有学习所有规则。
  • 我完全同意你的看法。然而,它只是 Java 以这种方式行事的唯一补充。当有人阅读这个列表时,他就会明白为什么设置“()”很重要,因为有很多优先级规则。
  • @Jon 实际上我很累打印两个字符串都为空或不在一行中
  • @Krushna ((s1 == null) && (s2 ==null)) ? "Both are null" : "At least one is not null"
【解决方案2】:

+== 之前得到处理。

这导致s1 == " " == null

【讨论】:

    猜你喜欢
    • 2016-02-27
    • 1970-01-01
    • 2011-01-29
    • 2016-01-25
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    相关资源
    最近更新 更多