I'm getting an error on my code and I really dont understand why it's happening:
for(Pacote<Par<String, Double>> pacote : pacotes) /snippet of code where the error occurs/
trying to cast it to
public class Pacote <E> {
private int capacidade;
private ArrayList <E> pacote;
public Pacote (int capacidade){
pacote= new ArrayList <> (capacidade);
this.capacidade=capacidade;
}
public Par (A itemA, B itemB){
this.tipo=itemA;
this.peso=itemB;
}
public A primeiro(){
return tipo;
}
public B segundo () {
return peso;
}
}
public class Pacote {
private int capacidade;
private ArrayList <E> pacote;
public Pacote (int capacidade){
pacote= new ArrayList <> (capacidade);
this.capacidade=capacidade;
}
public int getCapacidade (){
return capacidade;
}
public int getNumItems (){
return pacote.size();
}
public boolean estaCheio () {
return getNumItems()<capacidade-1;
}
public boolean empacota (E item){
if (estaCheio())
return false;
else {
pacote.add(item);
return true;
}
}
public List<E> items(){
List <E> list = pacote;
return list;
}
Code around the line it is happening:
public static void main(String[] args) throws IOException {
// Recebe os dados de input
Scanner sc = new Scanner(System.in);
System.out.println("Introduza o ficheiro com a lista de items a empacotar:");
String fich = sc.nextLine();
BufferedReader reader = new BufferedReader(new FileReader(fich));
System.out.println("Introduza a capacidade dos pacotes:");
int capacidade = Integer.parseInt(sc.nextLine());
// Cria os pacotes
List<Pacote<Par<String, Double>>> pacotes =
GestorPacotes.criaPacotes(reader, capacidade);
reader.close();
// Mostra a informacao dos pacotes
System.out.println("Pacotes formados:");
int index = 0;
for(Pacote<Par<String, Double>> pacote : pacotes) { /error here/
System.out.println("Pacote " + index++ + ":");
And I'm getting "Exception in thread "main" java.lang.ClassCastException: pack.Par cannot be cast to pack.Pacote", not sure why. Can someone help?
public static List<Pacote<Par<String, Double>>> criaPacotes(
BufferedReader fileReader, int capacidadePacotes)
throws IOException {
List retorno = new ArrayList <> (6);
String s;
while ((s=fileReader.readLine())!=null){
retorno.add(parseItem(s));
}
return retorno;
}
Your declaration of Par
is incorrect. I suppose you want it to be an inner class, but you haven't declared it as class.
public Par (A itemA, B itemB){
this.tipo=itemA;
this.peso=itemB;
}
This is a constructor, but it is treated as constructor to the surrounding class, with is Pacote
, not Par
, so you do not actually have a class Par
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.