【问题标题】:Using ArrayDeque Java使用 ArrayDeque Java
【发布时间】:2013-05-04 22:28:07
【问题描述】:

我正在尝试使用 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);
}
}

【问题讨论】:

  • java 没有integer。原语是int,对象是Integer
  • 另外,“遇到一些错误”对我们没有帮助。请提供错误。
  • 您能否详细说明“我遇到了一些错误”?
  • Array deques have no capacity restrictions; they grow as necessary to support usage
  • 我认为寻找素数的整个实现是不正确的!

标签: java storage arraydeque


【解决方案1】:

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

【讨论】:

  • 这不是更正确吗: Deque primes = new ArrayDeque(8); ???
  • 是的。谢谢你,@djangofan。
猜你喜欢
  • 2014-06-03
  • 2021-08-06
  • 2015-10-01
  • 2014-03-27
  • 2012-10-25
  • 2017-05-21
  • 2016-05-03
  • 2013-07-14
  • 2021-02-24
相关资源
最近更新 更多