使用 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/