首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ArrayDeque Java

使用ArrayDeque Java
EN

Stack Overflow用户
提问于 2013-05-10 17:14:27
回答 1查看 1K关注 0票数 1

我正在尝试用java存储质数列表,结果遇到了ArrayDeque。我不确定现在是否是使用它的正确时机,但由于我不知道素数的数量,所以我需要容量来增长。

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

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

非常感谢,贝扎德

代码语言:javascript
复制
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);
}
}
EN

回答 1

Stack Overflow用户

发布于 2013-05-10 17:20:00

在Java语言中,没有比integer更好的东西了。合适的是Integer

代码语言:javascript
复制
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);
 }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16478839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档