2015-03-03 50 views
0

我很努力在名爲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(); 
    } 
} 

回答

2

這時候你傳遞一個空字符串給第二個構造發生。在這種情況下,以下行將引發異常。

this.front = new node(original.charAt(0)); 

因爲chatAt(0)不存在(0不在邊界內)。你可以用這個構造函數的if來防止這種情況。