开发者

Java error "Undefined name"

I've tried fixing this I just cant seem to find a solution to this problem. The code is meant to print the prime numbers in a range, but it just returns the error

Static Error: Undefined name 'PrimeNumbers

Would anyone please be able to help me ?

This is my code :

import java.util.*;

public class PrimeNumbers { 

    private List<Integer> listOfPrimeNumbers;  //add a member variable for the ArrayList
    public static void main(String args []){    
      PrimeNumbers primeNumberList = new PrimeNumbers(50);
      primeNumberList.print();  //use our new print method
    }

public PrimeNumbers (int initialCapacity) {
    listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2);  //initialCapacity/2 is an easy (if not tight) upper bound
    long numberOfPrimes = 0; //Init开发者_Go百科ialises 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++;
        }
    }

  public void print() {
    int i = 1; 
    for (Integer nextPrime:listOfPrimeNumbers) {
      System.out.println("the " + i + "th prime is: " + nextPrime);
      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
}


Assuming, you have you code organized like this

./project
   PrimeNumbers.java
   PrimeNumbers.class

then you cd to ./project and type

java PrimeNumbers

Note - this only works because you didn't declare a package (iaw: you class is in the default package). Usually you have a package declaration and then it looks a bit different.


Bonus

The getter is a good idea, but you should think twice before returning a collection, because this way, you grant the receiver full access to your (internal?) datastructure and he can alter the values of that collection. And you shouldn't declare it with the raw type. Here's a better way to implement it:

public List<Integer> getPrimes() {
  return Collections.unmodifiableList(listOfPrimeNumbers);
}

Now the receiver knows that he get's a list of Integer values and can't modify the result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜