微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – ArrayList warning- warning:[unchecked]未选中调用add(E),也不会运行文件.请帮忙?

我一直试图让这段代码在这个阶段感觉像一个时代一样.它是为了计算一个范围内的素数,并且我已经写了一个打印它们的方法.不幸的是,代码不会编译,引用警告:

“warning:[unchecked]未选中调用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

这将消除警告.

奖金 – 您可能希望在打印方法中使用增强型for循环作为替代方法

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

原文地址:https://www.jb51.cc/java/123347.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐