【问题标题】:Java: No exception message errorJava:没有异常消息错误
【发布时间】:2014-04-05 11:46:00
【问题描述】:

使用 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));
    }

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

【问题讨论】:

    标签: java generics nullpointerexception bluej


    【解决方案1】:

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

    throw new IndexOutOfBoundsException();
    

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

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

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

    【讨论】:

    • 我将如何修复它,以免它返回 null?
    • @Hovering 首先,为什么要在无效索引上测试assertEquals()?你知道这会抛出一个异常,既然你期望这样,你应该断言一个异常。
    • 在从 String 更改代码之前,我使用了相同的测试代码,一切都按预期工作。我没有更改测试类中的任何内容,但它会返回错误?为什么会这样做?
    • 感谢 Rohit,我花了一段时间才了解我的测试代码在使用字符串时的区别,并注意到当我将代码更改为泛型时,我已经更改了代码以使其不正确。
    猜你喜欢
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多