gpt4 book ai didi

java - java中类型转换时出错

转载 作者:行者123 更新时间:2023-12-02 08:22:54 24 4
gpt4 key购买 nike

嘿伙计们,我正在尝试编写在 java 中进行类型转换,但我不断得到

run: 
[(E,1), (H,1), (F,2), (G,2), (I,5), ( ,7)]
(H,1)
class datacompression.tuple
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to datacompression.tuple
at datacompression.Chap3.huffman(Chap3.java:79)
at datacompression.Chap3.histogram(Chap3.java:37)
at datacompression.Main.main(Main.java:18)
Java Result: 1

这是源代码:

import java.util.ArrayList;

/**
*
* @author Cubearth
*/
public class Chap3 {

public static void huffman(ArrayList<tuple> list){
//creates an huffman tree
ArrayList<Node> huff = new ArrayList<Node>();
for(int i = 0; i<list.size(); i++){
huff.add(i, new Node(list.get(i), 2));
huff.get(i).setScore(list.get(i).getB());
}

System.out.println(huff.get(1).getData().toString());
System.out.println(huff.get(1).getData().getClass());
while(huff.size()>1){
String msg = ((tuple)(huff.get(0).getData())).getA()+ ((tuple)(huff.get(1).getData())).getA();
Node tmp = new Node(msg, 2);
tmp.setChild(huff.get(0), 1);
tmp.setChild(huff.get(1), 1);
tmp.setScore((huff.get(0).getScore()+huff.get(1).getScore()));
huff.set(0, tmp);
huff.remove(1);
sort2(huff);
}
System.out.println(huff);
Tree tmp = new Tree(huff.get(0));
tmp.print(2);
}

public static void sort2(ArrayList<Node> list){
//sort an arrayList of node, uesing insertion sort
int pos, min;
for(pos = 0; pos<list.size()-1; pos++){
min = pos;
for(int i = pos+1; i<list.size(); i++){
if(list.get(i).getScore()< list.get(pos).getScore())
min = i;
}
if(min!=pos){
swap2(list, pos, min);
}
}
}

public static void swap2(ArrayList<Node> list, int a, int b){
//swap two indexes of list
Node bucket = new Node(list.get(a).getData(), list.get(a).getNoc());
list.set(a, list.get(b));
list.set(b, bucket);
}
}

为什么我在 huffman 方法中对类的检查显示为 tuple(),但无法将其转换为一个?

最佳答案

嗯,最初 huff.get(0).getData() 可能作为“元组”出现,但在这一行中:

huff.set(0, tmp);

你将它设置为一个字符串(因为 tmp 是一个字符串),所以在下一次迭代中它会提示

关于java - java中类型转换时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5133613/

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