You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java条件if语句中为变量赋值?解决断言错误问题

Java条件方法断言错误排查与解决

我尝试在Java方法中将answer变量赋值为"Buying new shirt",但运行测试时出现断言错误,报错显示期望结果为null,实际得到Buying new shirt。

问题代码

public String simpleConditional(int price)  {
        String answer = null ;
price = 20;
          if (price < 20)
              System.out.println("Buying new shirt");
answer = "Buying new shirt"

测试报错信息

ConditionalStatementsTest > simpleConditionalTest(int, String) > com.ata.ConditionalStatements
Test.simpleConditionalTest(int, String)[3] FAILED                                             
    org.opentest4j.AssertionFailedError: expected: <null> but was: <Buying new shirt>         
        at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)                   
        at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)           
        at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)             
        at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)             
        at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)                 
        at com.ata.ConditionalStatementsTest.simpleConditionalTest(ConditionalStatementsTest.j

问题原因

  • 参数被硬覆盖:方法内直接执行price = 20;,完全忽略了外部传入的测试参数,导致条件判断失去意义。
  • 赋值逻辑错误:answer = "Buying new shirt"写在if块外面,不管条件是否成立都会执行,所以方法永远返回这个字符串,和测试用例中“当price≥20时返回null”的预期冲突。
  • 原代码还遗漏了return answer;语句,以及赋值语句末尾的分号,存在语法问题。

修复方案

  • 删除price = 20;,保留传入的原始参数进行判断。
  • 将answer = "Buying new shirt"移动到if代码块内部,仅当price < 20时才赋值。
  • 补充return answer;语句,确保方法返回结果;给赋值语句加上分号,修复语法错误。

修正后的代码示例

public String simpleConditional(int price)  {
    String answer = null;
    if (price < 20) {
        System.out.println("Buying new shirt");
        answer = "Buying new shirt";
    }
    return answer;
}

内容的提问来源于stack exchange,提问作者Terell Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:11:11