java - 使用 boolean 值在 Java 中实现素数筛

标签 java debugging compiler-errors boolean-operations

我正在尝试在Java中实现一个素数筛,以便我可以计算出小于某个最大值的所有素数的总和。我尝试使用 PrimeSieve 方法并使用 boolean 数组来实现此操作,如果通过取素数并考虑所有小于最大值的整数倍数来确定该数字是合数,则该 boolean 数组为真。

但是当我尝试运行该程序时,我不断收到编译器错误,并且我无法弄清楚出了什么问题:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error, insert ". class" to complete Expression The type of the expression must be an array type but it resolved to Class Syntax error on token "i", delete this token Syntax error, insert ". class" to complete Expression The type of the expression must be an array type but it resolved to Class
at Problem3.PrimeSieve(Problem3.java:11)
at Problem3.main(Problem3.java:26)

public class Problem3 {

    public static boolean[] PrimeSieve(int max) {

        // automatically all entries are false
        boolean[] isPrime = new boolean[max];

        // when a number isn't prime make the entry true

        for (int i = 0; i < max; i++) {
            if (!boolean[i]) {
                for (int j = 2i; j < max; j += i) {
                    boolean[j] = true;
                }
            } else {}
        }

        // return the isPrime boolean with all the primes as false
        return isPrime;
    }

    public static void main(String[] args) {

        boolean[] Primes = new boolean[100];
        Primes = PrimeSieve(100);

        int i = 0;
        int ans = 0;

        while (i < 100) {
            if (!Primes[i]) {
                ans += i;
                i++;
            } else { 
                i++; 
            }
        }

        System.out.println(ans);
    }
}

任何解决这些错误的帮助将不胜感激

最佳答案

您遇到了 2 个问题:
1) 您使用类型的名称而不是数组的名称。
所以 boolean[i] 应该改为 isPrime[i]
2) Java 不将 2i 理解为“两倍 i”。您需要编写 2*i

这将使您的代码编译:

 for (int i = 0; i < max; i++) {
                    if (!isPrime[i]) {
                        for (int j = 2*i; j < max; j += i) {
                            isPrime[j] = true;
                        }
                    } else {}  // By the way - This is really not necessary
                }

关于java - 使用 boolean 值在 Java 中实现素数筛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45266711/

相关文章:

java - toString() 方法打印空值

.net - .NET PDB文件的格式(模式)是什么?

delphi - 使用 `in` 关键字会导致 Delphi 中出现 "E1012 Constant expression violates subrange bounds"

java - iText 单元格宽度似乎表现不一致

java - 将javafx中的文本字段加密

ios - Xcode Debug View Hierarchy 查找 viewcontroller

c# - `CrossPlatformInput' 在命名空间 `UnitySampleAssets' 中不存在

c++ - 为什么 VC++ 2013 不支持 promise 的非静态数据成员初始值设定项

java - 是否可以使用 run-forked 从不同的 JVM 运行 Jetty?

java - 如何在 Eclipse 中将源附加到 Web 应用程序库?