1

我正在尝试使用 java 存储素数列表并遇到 ArrayDeque。我不确定这是否是使用它的正确场合,但由于我不知道素数的数量,我需要增加容量。

该代码旨在遍历数字 2 到 1000 并测试它们是否为质数。

我遇到了一些错误。我对此很陌生,所以如果有人能引导我朝着正确的方向前进,那就太好了。使用具有较大预设容量的阵列是一种更好的做事方式吗?

非常感谢,贝扎德

import java.util.ArrayDeque;
import java.util.Deque;

public class Maths {
public static void main (String[] arg) {        

    int x = 2;
    ArrayDeque<integer> primes = new ArrayDeque<integer>(8);

    for(int count = 2; count<1000; count++) {
        if (x%count == 0) {
            System.out.println("Number is not prime"); // If it isn't a prime, it moves onto the next number.
            x = x + 1;
            count = 2;
        }

        else if (x >1000) {
            break;
        }

        else if (count == x - 1) {
            System.out.println( x + " is a prime"); //This possibility singles out prime numbers
            primes.add(x);
            x = x + 1;                              // Need to find a way to add them to memory.
            count = 2;
        }
    }
    System.out.println("Searchfinished");
    System.out.println(primes);
}
}
4

1 回答 1

3

Java 中没有类似integer. 正确的是Integer

import java.util.ArrayDeque;
public class MyClass {
  public static void main(String args[]) {

    int x = 2;
    Deque<Integer> primes = new ArrayDeque<Integer>(8);

    for(int count = 2; count<1000; count++) {
      if (x%count == 0) {
          System.out.println("Number is not prime"); // If it isn't a prime, it moves onto the next number.
          x = x + 1;
          count = 2;
      } else if (x > 1000) {
          break;
      } else if (count == x - 1) {
          System.out.println( x + " is a prime"); //This possibility singles out prime numbers
          primes.add(x);
          x = x + 1;                              // Need to find a way to add them to memory.
          count = 2;
      }
  }
  System.out.println("Searchfinished");

  System.out.println(primes);
 }
}
于 2013-05-10T09:19:59.833 回答