Java错误“未定义的名称”
问题描述:
我试过修复这个问题,我只是无法找到解决这个问题的方法。该代码旨在打印范围内的素数,但它只是返回错误Java错误“未定义的名称”
Static Error: Undefined name 'PrimeNumbers
请问谁能帮我?
这是我的代码:
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; //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++;
}
}
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
}
答
假设,你有你的代码组织这样
./project
PrimeNumbers.java
PrimeNumbers.class
那么你cd
到./project
并键入
java PrimeNumbers
注意 - 这只适用于因为您没有申报包裹(iaw:您的课程为,默认包装为)。通常你有一个包装声明,然后它看起来有点不同。
奖金
吸气是个好主意,但返回集合之前应该三思而后行,因为这样一来,您授予接收机完全访问你的(内部?)数据结构和他可以改变该集合的值。你不应该用原始类型来声明它。下面就来实现它有更好的方式:
public List<Integer> getPrimes() {
return Collections.unmodifiableList(listOfPrimeNumbers);
}
现在接收器知道,他得到的Integer
值的列表,并不能修改的结果。
你如何启动你的代码? – 2010-11-29 13:17:56