比较解析的整数值返回错误的java

时间:2014-12-07 21:53:35

标签: java

我有一个genreic对象Class。当我向对象添加整数并比较它们时,它返回错误的答案。

    bsTree<Integer> tree = new bsTree<Integer>();
    tree.add(6);

然后在比较中

add(T value) {
Node nodeWithData = root;

System.out.println(Integer.parseInt(value.toString) <= Integer.parse(nodeWithData.getContent().toString())
}

节点内容等于5,但它打印为true。为什么呢?

编译的当前代码

public class bsTree<T> {
private bNode root;
private bNode currentNode = root;


public bsTree()
{
    root = null;
}
public bsTree(T[] anArray)
{
    if(anArray==null)
    {
        return;
    }
    for(int i = 0; i<anArray.length; i++)
    {
        add(anArray[i]);
    }
}

public void add(T value)
{

    if(root == null)
    {
        System.out.println("Setting first node to " + value);

        root = new bNode(value);
        return;
    }
    else
    {
        //System.out.println("Value is = " + value);            
        currentNode = root;

        while(currentNode != null)
        {
            if(Integer.parseInt(currentNode.getContent().toString()) <= Integer.parseInt(value.toString()))
            {
                System.out.println(value + " <= " + currentNode.getContent());

                if(currentNode.getlChild() == null)
                {
                    System.out.println("Setting left Child");
                    currentNode.setlChild(new bNode(value));
                    return;
                }
                else
                {
                    System.out.println("Going left");
                    currentNode = currentNode.getlChild();
                }

            }
            else
            {

            }

        }

    }

}

public static void main(String[] args)
{
    bsTree<Integer> tree = new bsTree<Integer>();

    tree.add(5);
    tree.add(6);
    tree.add(7);
    tree.add(8);
    tree.add(9);

}


}

1 个答案:

答案 0 :(得分:2)

您正在打印与测试相反的内容。您测试currentNode&lt; = value,但打印相反。

if(Integer.parseInt(currentNode.getContent().toString()) <= 
    Integer.parseInt(value.toString()))
{
  System.out.println(value + " <= " + currentNode.getContent());

应该是

if(Integer.parseInt(currentNode.getContent().toString()) <= 
    Integer.parseInt(value.toString()))
{
  System.out.println(currentNode.getContent() + " <= " + value);