【问题标题】:Trouble comparing string's in java [duplicate]在java中比较字符串时遇到问题[重复]
【发布时间】:2014-02-10 07:27:29
【问题描述】:

为什么返回 true?

String b =  "(5, 5)";
String a =  "(7, 8)" ;
if(a.equals(b));
{

    System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}

输出:

Somehow "(7, 8)" and "(5, 5)" are the same

【问题讨论】:

标签: java string if-statement boolean


【解决方案1】:

您的代码相当于:

if(a.equals(b)) { }
{
   System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}

因此,无论条件如何,块中的打印语句都会始终执行,因为if 的主体不包含该语句。

JLS - 14.6. The Empty Statement

空语句什么都不做

空语句:

; 

空语句的执行总是正常完成

【讨论】:

  • 啊……语言规范。
  • 我正要发布这个链接!!编辑:@sᴜʀᴇsʜᴀᴛᴛᴀ 阅读此stackoverflow.com/a/14112532/1673391
  • 速度与激情......
  • @GrijeshChauhan 这是一个有用的链接。
  • 他穿越到了未来,偷走了我的链接。
【解决方案2】:

你的 if 语句后面有 ;

使用:

if(a.equals(b)) {
    System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}

看看this answer

【讨论】:

  • 解释一下当你把分号放在那里时会发生什么可能会有所帮助。
【解决方案3】:
if(a.equals(b));<-----

你有一个 extre ;在那里,语句到此结束。

这就像写作

if(a.equals(b));

这里有一个块

{

    System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}

所以摆脱多余的;

【讨论】:

  • 这里是一个静态块 - 它不是一个静态块,AFAIK。
  • @Ɍ.Ɉ 那么你怎么看?你能纠正我吗?
  • 这是一个anonymous block。这是一个静态块 - static { ... }
  • @Ɍ.Ɉ 我通常指的是静态的:)。有充分的理由改变它。谢谢。
【解决方案4】:

您的 if 条件已满足,但自 ; 之后不会执行任何操作。

if(a.equals(b)); // ;  this is equal to if(a.equals(b)){}

如下更正

if(a.equals(b)){
 System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
}    

【讨论】:

    【解决方案5】:

    因为您在 if 语句之后键入了 ;。然后它会被评估为if(a.equals(b)){};,这意味着什么都不做。

    String b =  "(5, 5)";
    String a =  "(7, 8)" ;
    if(a.equals(b)); <-- remove this ';'
    {
        System.out.printf("Somehow \"%s\" and \"%s\" are the same" ,a,b);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多