微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 在switch语句中使用逻辑

我的问题与以下代码有关:
public static void main(String[] args) {

    // Find Prime Numbers from 0 to 100
    int i;
    for (i=2; i <= 100; i++) {
        int j = 2;
        boolean iPrime = true;

        //The following line gives incorrect results,but should execute faster
        //  while ((iPrime = true) && (j < (i / 2 + 1))) {
        //The following line gives correct results but performs un-necessary operations
        //by continuing to calculate after the number is found to be "not prime"
        while (j < (i / 2 + 1)) {

            j++;
            if ((i % j) == 0) {
                iPrime = false;
                //System.out.println(j + " is a factor of " + i);
            }
        }
        if (iPrime) {
            System.out.println(i + " is a prime number!");
        }
    }
}

现在,正如我在代码中所评论的那样,我想要实现的是通过仅在iPrime = true时执行’while’循环来更快地执行我的程序. 50%的数字可被2整除,因此一旦确定,计算就可以停止.

我正在从一本书中做这个项目作为初学者’例子的一部分’,我实际上是想尽可能快地计算高达1000000只是因为我自己的“额外信用”……

我读到了“短路”和“运算符”&&如果前半部分为真,则仅评估语句的后半部分,如果为假,则两者不相互评估(节省cpu)

它也将退出循环,这将节省更多的cpu ……

但由于某种原因,它无法正常工作!我在整个过程中添加了更多的System.out.println()语句,列出了’iPrime’是什么 – 输出是奇怪的……它打开和关闭iPrime并评估每个数字,这是我无法理解的.

解决方法

if((iPrime = true)&& …)应该是if((iPrime)&& …).

通过执行isPrime = true,您可以为isPrime指定true,而不是将其’value’与true进行比较.

您可能还希望看到this以更好地了解代码中发生的情况:

At run time,the result of the assignment expression is the value of
the variable after the assignment has occurred. The result of an
assignment expression is not itself a variable.

所以,当你使用=运算符而不是==(当你将某些东西与true进行比较时删除它 – 而不是写if(someBoolean == true)你只写if(someBoolean)),你实际上是满足条件,总是!

原文地址:https://www.jb51.cc/java/126775.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐