加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在switch语句中使用逻辑

发布时间:2020-12-15 00:06:38 所属栏目:Java 来源:网络整理
导读:我的问题与以下代码有关: 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
我的问题与以下代码有关:
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)),你实际上是满足条件,总是!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读