Java:没有异常消息错误

标签 java generics nullpointerexception bluej

使用 BlueJ,对 java 来说还是个新手。当我运行测试时遇到问题,它返回说“没有异常消息”。我不知道在哪里查看我的代码来解决这个问题。所以这是我到目前为止所拥有的:

主类

public class LList<X>
{
    private Node<X> head;
    private int length = 0;

public int size()
{
    return length;
}

public void add(X item)
{
    Node a = new Node();
    a.setValue(item);
    a.setLink(head);
    head = a;
    length ++;
}

public X get(int index)
    {
        X holder = null;
        Node<X> h = head;
        if(index > length)
        {
            throw new IndexOutOfBoundsException();
        }
        else
        {
            for(int i = 0; i < index + 1; i++)
            {
                h = h.getLink();
                holder = h.getValue();
            }
            return holder;
        }

    }
}

下一个类

 public class Node<X>
{
    private X value;
    private Node link;

    public X getValue()
    {
        return value;
    }

    public void setValue(X v)
    {
        value = v;
    }

    public void setLink(Node l)
    {
        link = l;
    }

    public Node getLink()
    {
        return link;
    }    
}

测试类

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class LListTest


@Test
    public void testGet()
    {
        LList x = new <String>LList();
        x.add("hi");
        assertEquals("hi", x.get(0));
        x.add("1hi");
        assertEquals("hi", x.get(1));
        assertEquals("1hi", x.get(0));
        x.add("2hi");
        assertEquals("hi", x.get(2));
        assertEquals("1hi", x.get(1));
        assertEquals("2hi", x.get(0));
        x.add("3hi");
        assertEquals("hi", x.get(3));
        assertEquals("1hi", x.get(2));
        assertEquals("2hi", x.get(1));
        assertEquals("3hi", x.get(0));
        x.add("4hi");
        assertEquals("hi", x.get(4));
        assertEquals("1hi", x.get(3));
        assertEquals("2hi", x.get(2));
        assertEquals("3hi", x.get(1));
        assertEquals("4hi", x.get(0));
    }

如果有任何想法,我将不胜感激,无论是解释我的代码中问题所在的位置,还是解释我为什么会收到错误都会很棒。

最佳答案

当您尝试访问无效索引时,会抛出异常:

throw new IndexOutOfBoundsException();

没有任何消息。因此,其中包含的异常消息将为 null。然后调用以下 assertEquals():

assertEquals("hi", x.get(4));

将失败,因为x.get(4)将抛出异常,但消息将为null

关于Java:没有异常消息错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22163520/

相关文章:

java - 记录 NullPointerException?

Java 并发迭代 : Divide and Conquer vs Runnable for each item

Java 游戏对象设计

java - 通过 Java 从 Postgresql 获取返回值

generics - 实现拥有和借用的特征

Java 空指针检查以加快代码执行速度

java - 如果所有消费者都以相同的方式使用相同的 API,为什么我们应该为每个消费者准备 1 个 Pact 文件?

c# - 泛型和集合继承

java - 将数据从android添加到mysql数据库时出现NullPointer异常