使用ArrayDeque Java

时间:2013-05-10 09:14:27

标签: java storage arraydeque

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

该代码旨在通过数字2到1000并测试它们是否是素数。

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

非常感谢, Behzad

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);
}
}

1 个答案:

答案 0 :(得分: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);
 }
}