我认为构造函数在逻辑上是正确的,我只是无法弄清楚如何在main中调用它! :)有人可以帮忙吗?如果有人只是快速查看我的代码就会很好:)非常感谢!
另外,我在这个实现中使用arrayLists,我必须这样做,所以我不想改变它,即使它只使用数组更容易实现。
import java.util.*;
public class PrimeNumberss {
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(10);
}
public PrimeNumberss (int initialCapacity) {
ArrayList<Integer> listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
}
答案 0 :(得分:3)
答案 1 :(得分:1)
i == initialCapacity显然是错误的。
答案 2 :(得分:0)
一切都很重要,它的变化很小。现在你得到的素数小于N,所以如果你想把它改成N个素数,这将是一个真正的功能差异。现在让我们让N = 50,这样你就可以获得超过10个素数。
public class PrimeNumberss {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(50);
PrimeNumbers.print(); //use our new print method
}
public PrimeNumberss (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
//.... complete the constructor method as you have it. honestly, i didnt even read it all
public void print() //add this printout function
{
int i = 1;
it = listOfPrimeNumbers.listIterator();
while (it.hasNext())
{
System.out.println("the " + i + "th prime is: " + it.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
另一方面,你可能会更好地命名(PrimeNumberss和PrimeNumbers ??),但我没有改变任何一个。此外,intiialCapacity并未反映它的真正含义。也许就像“顶级”一样。