gpt4 book ai didi

Java,找不到符号并且无法从数组列表中提取数据类型

转载 作者:行者123 更新时间:2023-11-29 03:25:21 27 4
gpt4 key购买 nike

    public class Packages 
{
private ArrayList shipmentList = new ArrayList();
private double totalWeight;

public Packages(String shiplist) throws IOException
{
Scanner scanFile = new Scanner(new File(shiplist));
scanFile.useDelimiter("\n");
while(scanFile.hasNext() == true){
String pack = scanFile.next();
Scanner splitter = new Scanner(pack);
splitter.useDelimiter(" ");
int id = splitter.nextInt();
double weight = splitter.nextDouble();
String state = splitter.next();
shipmentList.add(new Packet(id, weight, state));
}
this.totalWeight = 0;

}

public String toString()
{String allShipments ="";
for(int i =0;i<shipmentList.size();i++)
allShipments += shipmentList.get(i) + "\n";
return allShipments;
}
//needs work. Cannot find method isLight() from class packet, yet toString() fires fine.
public void displayLightPackages()
{
for (int i=0;i<shipmentList.size();i++){
Packet thisShipment = shipmentList.get(i);
if(thisShipment.isLight() == true){
System.out.println("Package: "+ shipmentList.get(i).toString()+" Is light.");
}else{
System.out.print("");
}
}
}

方法 displayLightPackages() 给我错误。这是数据包类:

public class Packet
{
// instance variables - replace the example below with your own
private int idNumber;
private double weight;
private String state;

public Packet(int idNumber, double weight, String state)
{
this.idNumber= idNumber;
this.weight = weight;
this.state = state;
}
public boolean isHeavy()
{
return (weight>10);
}
public boolean isLight()
{
return (weight<10);
}
public String toString()
{
return "ID: "+idNumber+" WEIGHT: "+weight+" STATE: "+state;
}
}

方法 toString 在从 main 方法调用时可以正常触发,但是,我无法访问 Packet 类中的任何其他方法。构造函数在将数据包添加到包含所有数据包的 Arraylist 时起作用。我尝试用

在 displayLightPackages 中定义一个数据包
Packet thisShipment = shipmentList.get(i);

但是我得到一个不兼容的类型错误。刚用代码的时候

shipmentList.get(i).isLight()

在 displayLightPackages 方法中,我收到编译器无法找到符号 isLight 的错误。我怀疑该错误与数组列表中的数据类型有关,但除此之外,此时我不知所措。

谢谢

最佳答案

您的 ArrayList 没有类型化,因此来自它的所有内容都是一个 Object。相反,Object 没有 isLight() 方法,因此会出现“找不到符号”错误。

要解决此问题,请键入您的 ArrayList...

private ArrayList<Packet> shipmentList = new ArrayList<>();

... 或在使用 get 时转换为 Packet:

((Packet)shipmentList.get(i)).isLight()

在这两个选项中,键入 ArrayList 更简单、更安全,因为您不必每次从中获取值时都记得进行转换。

关于Java,找不到符号并且无法从数组列表中提取数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21355818/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com