gpt4 book ai didi

java - ArrayList 警告 - 警告 : [unchecked] unchecked call to add(E), 文件也不会运行

转载 作者:太空狗 更新时间:2023-10-29 22:42:14 30 4
gpt4 key购买 nike

我一直在努力让这段代码适用于现阶段的年龄。它旨在计算一个范围内的素数,我已经编写了一种方法来打印它们。不幸的是,代码将无法编译,引用警告:

“警告:[未检查] 未检查调用 add(E) 作为原始类型 java.util.List 的成员”

--我从谷歌搜索中了解到,这个警告是为了不声明你的错误中应该有什么类型的值,但我已经这样做了,而且这个错误似乎只在我尝试使用 .add() 时出现在我的数组列表上运行。

当我尝试运行它时,它给出了一个更可怕的错误“静态错误:未定义名称‘PrimeNumbers’

我认为此时我已经代码盲了,尽管进行了多次尝试,但仍无法找出我做错了什么。

import java.util.*;

public class PrimeNumbers {

private List 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() //add this printout function
{
int i = 1;
Iterator iterator = listOfPrimeNumbers.listIterator();
while (iterator.hasNext())
{
System.out.println("the " + i + "th prime is: " + iterator.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
}

最佳答案

改变这一行

private List listOfPrimeNumbers;  //add a member variable for the ArrayList

private List<Integer> listOfPrimeNumbers;  //add a member variable for the ArrayList

这将消除警告。


好处 - 您可能想在 print 方法中使用增强的 for 循环 作为替代方法:

public void print() {
int i = 1;
for (Integer nextPrime:listOfPrimeNumbers) {
System.out.println("the " + i + "th prime is: " + nextPrime);
i++;
}
}

关于java - ArrayList 警告 - 警告 : [unchecked] unchecked call to add(E), 文件也不会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4303511/

30 4 0