【问题标题】:JAVA code in Android Studio not executing if statementAndroid Studio 中的 JAVA 代码未执行 if 语句
【发布时间】:2025-12-26 18:35:07
【问题描述】:

我很难弄清楚为什么以下代码中的 if 语句没有正确执行:

double yint = -157.42;
if(copy_denominator.contains("x^"+nextBottom))yint = -1*constant / d2;

Log.d(PERIOD,"copy den: "+copy_denominator +" yint "+yint);
//the Log statement above prints out that yint = 3.0;

if(yint != -157.42)
Log.d(PERIOD,"oblique 5 "+slope+"x + "+yint);//I expect this to print to Log

if(yint == -157.42)Log.d(PERIOD,"oblique 6 "+slope+"x ");//This prints out.

我不知道为什么语句: if(yint != -157.42) 不执行。 我以前从未见过这个,这可能是Android Studio中的一个错误。

感谢您的建议

【问题讨论】:

  • 你的代码格式很糟糕。同样使用 == 和 != 与浮点常量进行比较也不是一个好主意。而是在比较时允许一些误差范围。此外,不要命名双“yint”类型的变量。您还确定它会打印出“yint = 3.0;”吗?希望这可以帮助。祝您问题得到解答。
  • 我认为您可能是正确的。让我看看如何尝试这种误差范围计算。 @user643011
  • 是的,它会打印出 "yint = 3.0" @user643011 。我尝试通过设置 yint = 157.42 并使用 if(Math.abs(157.42 - yint) > 0.001) 来纠正,但它仍然没有执行!
  • 不应该是if(Math.abs(-157.42 - yint) > 0.001) 吗?请编辑原始问题以反映新代码,并格式化代码以提高可读性。

标签: android if-statement logic


【解决方案1】:

这是一个非常奇怪的问题。您可以发布更多关于上下文的代码快照。以下是我的上下文快照。希望能帮助别人和你:

Android Studio 2.3.3

compileSdkVersion 25

buildToolsVersion "25.0.2"

minSdkVersion 16

targetSdkVersion 25

    public class MainActivity extends AppCompatActivity {

    private final String PERIOD = "PERIOD";

    private ArrayList<String> copy_denominator = new ArrayList<>();
    private int nextBottom = 2;
    private final double constant = 6.0D;
    private double d2 = 2.0D;
    private String slope = "2.3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        copy_denominator.add("x^2");

        double yint = -157.42;
        if (copy_denominator.contains("x^" + nextBottom)) yint = -1 * constant / d2;

        Log.d(PERIOD, "copy den: " + copy_denominator + " yint " + yint);
        //the Log statement above prints out that yint = 3.0;

        if (yint != -157.42)
            Log.d(PERIOD, "oblique 5 " + slope + "x + " + yint);//I expect this to print to Log

        if (yint == -157.42) Log.d(PERIOD, "oblique 6 " + slope + "x ");//This prints out.

    }
}

日志没问题:

[Logcat prints][1]

日志:

08-09 19:49:21.792 12323-12323/io.github.dkbai.appdemo D/PERIOD: copy den: [x^2] yint -3.0

08-09 19:49:21.792 12323-12323/io.github.dkbai.appdemo D/PERIOD: oblique 5 2.3x + -3.0

【讨论】: