我正在努力在名为的对象中构建链接列表构造函数LString
。构造函数从链接列表而不是数组中构建字符串。另一个文件测试该对象以验证其功能,当我使用构造函数和toString()
方法运行该文件时,收到此错误:
Running constructor, length, toString tests (10 tests)
Starting tests: ..FF......
Time: 0.00
2 failures:
1) t02aEmptyConstructorIsEmptyString(LStringTest$EmptyStringTest)
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
... 1 more
at LString.<init>(LString.java:45)
at LStringTest$EmptyStringTest.t02aEmptyConstructorIsEmptyString(LStringTest.java:193)
... 9 more
2) t02bEmptyConstructorHasZeroLength(LStringTest$EmptyStringTest)
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
... 1 more
at LString.<init>(LString.java:45)
at LStringTest$EmptyStringTest.t02bEmptyConstructorHasZeroLength(LStringTest.java:198)
... 9 more
Test Failed! (2 of 10 tests failed.)
我相信我在正确地建立链表,并且LString
错误地创建了一个对象,尽管我很难找出原因。感谢您尝试学习Java的任何建议。
这是我的代码:
public class LString {
node front;
int size;
private class node {
char data;
node next;
public node (){
}
public node (char newData){
this.data = newData;
}
public node (char newData, node newNext){
this.data = newData;
this.next = newNext;
}
}
public LString(){
this.size = 0;
this.front = null;
}
public LString(String original) {
this.size = original.length();
this.front = new node(original.charAt(0));
node curr = this.front;
for (int i =1; i < original.length(); i++) {
curr.next = new node(original.charAt(i));
curr = curr.next;
}
}
public String toString(){
StringBuilder result = new StringBuilder();
node curr = front;
while (curr != null){
result.append(curr.data);
curr = curr.next;
}
return result.toString();
}
}
当您将空字符串传递给第二个构造函数时,会发生这种情况。在这种情况下,以下行将引发异常。
this.front = new node(original.charAt(0));
因为chatAt(0)
不存在(0超出范围)。您可以使用if
防止这种情况的条件来保护此构造函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句