【问题标题】:My program should calculate prime numbers, but stops after the first number我的程序应该计算素数,但在第一个数字之后停止
【发布时间】:2017-11-23 13:46:20
【问题描述】:

所以我写了这个小程序,它应该检查一个数字是否是质数,如果是的话,应该将它添加到一个数组列表中。问题是它只是添加数字 3 然后停止。有人可以解释一下为什么会这样吗?

import java.util.ArrayList;
public class main{
    public static void main(String args[]){
        ArrayList Primzahlen=new ArrayList();
        int current=1;
        boolean prim=true;
        for(int a=0;a<100;a++){
            for(int b=2;b<current;b++){
                if(current%b==0){
                    prim=false;
                }
                if(b==current-1){
                    if(prim==true){
                        Primzahlen.add(current);
                    }
                }
            }
            current++;
        }
        System.out.println(Primzahlen);
    }
}

【问题讨论】:

  • 您应该尝试在调试器中单步执行您的代码。
  • 你设置了prim=false if current%b==0 但你再也没有将它设置为true。
  • 谢谢。我想我不应该错过这么明显的错误。
  • 犯“愚蠢”的错误是正常的。但是你需要学习如何通过调试来识别它们。你不能永远依赖别人为你找出错误。
  • boolean prim=true;移到内部循环之前。

标签: java if-statement arraylist boolean primes


【解决方案1】:

检查完当前值后,您需要将 prim 重置为 true。

public static void main(String args[]){
        ArrayList Primzahlen=new ArrayList();
        int current=1;
        boolean prim=true;
        Primzahlen.add(2);
        for(int a=3;a<100;a++){
            for(int b=2;b<current;b++){
                if(current%b==0){
                    prim=false;
                }
                if(b==current-1){
                    if(prim==true){
                        Primzahlen.add(current);
                    }
                }
            }
            prim=true;
            current++;
        }
        System.out.println(Primzahlen);
    }

注意 current++ 附近的 prim=true

【讨论】:

  • 或者只是将boolean prim=true; 下移一行,正如@saka1029 在 cmets 中所建议的那样。
  • 解决问题的方法很多。我在看到评论之前发布了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 2022-12-05
  • 2017-11-22
  • 1970-01-01
相关资源
最近更新 更多