【问题标题】:Method doesnt return after if statement even though the condition is definitely true [duplicate]即使条件肯定为真,方法在 if 语句之后也不会返回 [重复]
【发布时间】:2018-07-21 10:07:54
【问题描述】:

此方法在每次使用 SurfaceView 刷新屏幕时将一些文本呈现到 Canvas 上,并且应该在数据库光标关闭时返回 (if cursorClosed)。但正如您从 LogCat 中看到的那样,它没有。即使cursorClosed 为真,正如System.out.println(cursorClosed) 调用所证明的那样,当它应该在if 语句之后返回时,它也会到达此调用。谁能向我解释为什么会这样?感谢您的每一个提示!

这是我的代码:

public void present(float deltaTime) {
        Graphics graphics = game.getGraphics();
        graphics.drawBackground(Assets.background);
        if (cursorClosed)
            return;
        System.out.println(cursorClosed);
        if (picture != null) {
            graphics.drawPixmap(picture, 40, 280, 50);
        }
        if (!translated) {
            graphics.renderText(14, cursor.getString(1), 160, 300);
        } else {
            System.out.println("cursorClosed: " + cursorClosed);
        graphics.renderText(14, cursor.getString(2), 160, 300);
        graphics.drawPixmap(Assets.nextButton, 250, 310, 420);
    }
}

这是 LogCat:

07-20 19:21:25.950 21343-21378/com.melonman.wordsandphrases I/System.out: false
07-20 19:21:25.950 21343-21343/com.melonman.wordsandphrases I/System.out: 1
07-20 19:21:25.950 21343-21378/com.melonman.wordsandphrases I/System.out: cursorClosed: true
07-20 19:21:25.950 21343-21378/com.melonman.wordsandphrases E/AndroidRuntime: FATAL EXCEPTION: Thread-35292
Process: com.melonman.wordsandphrases, PID: 21343
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.database.Cursor.getString(int)' on a null object reference
    at com.melonman.wordsandphrases.wordsandphrasesapp.LessonScreen1.present(LessonScreen1.java:83)
    at com.melonman.wordsandphrases.framework.impl.AndroidFastRenderView.run(AndroidFastRenderView.java:46)
    at java.lang.Thread.run(Thread.java:818)

【问题讨论】:

  • 什么是“光标关闭”?我看不到它已在您的代码中初始化。也许首先检查是否不为空
  • @K.Kempski - 如果它是可空类型,代码将无法编译。
  • 日志输出清楚的显示是false刚刚被测试,只有true后来。很明显,在此期间有些东西正在改变它的价值。 (可能与 1 记录的内容相同。)
  • @T.J.Crowder 我认为这个问题不是重复的,至少不是因为您提供的原因。这是一个最终到达 NullPointrException 的逻辑问题。 OP 认为他的代码会返回并且不明白为什么没有。这正是您在评论中提到的。
  • @mTak - 没有投票决定关闭为重复。 This is one of my pet peeves about SO。我投票决定以非复制/未来无用的方式关闭,因为问题询问为什么 if 没有测试 true,答案显然是“因为它不是 true 在时间。”

标签: java android methods


【解决方案1】:

这段代码:

    if (cursorClosed)
        return;
    System.out.println(cursorClosed);

打印 false 这就是 return 语句不执行的原因。

这段代码:

    if (!translated) {
        graphics.renderText(14, cursor.getString(1), 160, 300);
    } else {
        System.out.println("cursorClosed: " + cursorClosed);

打印cursorClosed: true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2015-03-21
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多