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)),你实际上是满足条件,总是!

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...