2016-02-12 4 views
0

Im первая майка CS, и мне интересно, можете ли вы помочь мне очистить метод append (StringBuilder b) в моем классе MyStringBuilder. Ive проследил проблему до последнего раза, когда я пытаюсь добавить и добавить между связанными списками в моей программе тестовых драйверов. Я вставил отладочные заявления на печать на каждом шаге перед ними и, похоже, работает нормально ... Каждый объект построителя строк должен все еще существовать независимо друг от друга. Благодаря!присоединение связанного списка к другому связанному списку

//SAMPLE OUTPUT (what its supposed to be) 
**Testing constructor methods 
this is a string 
another string 

Testing Append methods 
this is a string another string 
this is a string another string and another 
this is a string another string and another another string 
this is a string another string and another another string!! 
another string different strings? 
...appending data** 

//MY CURRENT OUTPUT 
**Testing constructor methods 
this is a string 
another string 


Testing Append methods 
this is a string another string 
this is a string another string and another 
this is a string another string and another another string 
this is a string another string different strings? 
another string different strings? 
...appending data** 

МОЙ STRING СТРОИТЕЛЬ КЛАСС THUS FAR

public class MyStringBuilder 
{ 
    private CNode firstC; //first character node 
    private CNode lastC; //last character node 
    private int length; //length of mystringbuilder object 

public MyStringBuilder(String s) //this one should is correct since it was given! 
    { 
     if (s == null || s.length() == 0) // Special case for empty String 
     {         // or null reference 
      firstC = null; 
      lastC = null; 
      length = 0; 
     } 
     else 
     { 
      // Create front node to get started 
      firstC = new CNode(s.charAt(0)); 
      length = 1; 
      CNode currNode = firstC; 
      // Create remaining nodes, copying from String. Note 
      // how each new node is simply added to the end of the 
      // previous one. Trace this to see what is going on. 
      for (int i = 1; i < s.length(); i++) 
      { 
       CNode newNode = new CNode(s.charAt(i)); 
       currNode.next = newNode; 
       currNode = newNode; 
       length++; 
      } 
      lastC = currNode; 
     } 
    } 

    // Create a new MyStringBuilder initialized with the chars in array s 
    public MyStringBuilder(char [] s) 
    { 
     if (s == null || s.length == 0) // Special case for empty char array 
     {         // or null reference 
      firstC = null; 
      lastC = null; 
      length = 0; 
     } 
     else 
     { 
      // Create front node to get started 
      firstC = new CNode(s[0]); 
      length = 1; 
      CNode currNode = firstC; 
      // Create remaining nodes, copying from char array. 
      for (int i = 1; i < s.length; i++) 
      { 
       CNode newNode = new CNode(s[i]); 
       currNode.next = newNode; 
       currNode = newNode; 
       length++; 
      } 
      lastC = currNode; 
     } 
    } 


    // Create a new empty MyStringBuilder 
    public MyStringBuilder() 
    { 
     firstC=null; 
     lastC=null; 
     length=0; 
    } 


    // Append MyStringBuilder b to the end of the current MyStringBuilder, and 
    // return the current MyStringBuilder. Be careful for special cases! 
    public MyStringBuilder append(MyStringBuilder b) 
    { 
     if(length==0) 
     { 
      firstC = new CNode(b.firstC.data); 
      length = 1; 
      CNode currNode = b.firstC; 
      for (int i = 1; i < b.length; i++) 
      { 
       CNode newNode = new CNode(currNode.next.data); 
       currNode.next = newNode; 
       currNode = newNode; 
       length++; 
      } 
      lastC = currNode; 

     } 
     else{//works 
      CNode currNode = lastC; 

      CNode newNode = b.firstC; 
      for (int i = 1; i < b.length+1; i++) 
      { 
       currNode.next = newNode; 

       currNode = newNode; 

       newNode = currNode.next; 

       length++; 
      } 
      lastC = currNode; 
     } 
     return b; 
    } 

    // Append String s to the end of the current MyStringBuilder, and return 
    // the current MyStringBuilder. Be careful for special cases! 
    public MyStringBuilder append(String s) 
    { 
     if (s == null) // Special case for null ref 
     { 
      throw new NullPointerException("attempting to add empty string"); 
     } 
     else // non null ref 
     { 
      //convert string argument to temp char array to be passed into nodes 
      char [] tempCArray = s.toCharArray(); 
      if (isEmpty()) // if stringbuilder is empty 
      { 
       // Create front node to get started 
       firstC = new CNode(tempCArray[0]); 
       length = 1; 
       CNode currNode = firstC; 

       // Create remaining nodes, copying from temp char array. 
       for (int i = 1; i < tempCArray.length; i++) 
       { 
        CNode newNode = new CNode(tempCArray[i]); 
        currNode.next = newNode; 
        currNode = newNode; 
        length++; 
        lastC = currNode; 
       } 
      } 
      //is stringbuilder is not empty 
      else { 
       CNode currNode = lastC; 
       //if string builder is not empty 
       // Create nodes, copying from temp char array. 
       for (int i = 0; i < tempCArray.length; i++) { 
        CNode newNode = new CNode(tempCArray[i]); 
        currNode.next = newNode; 
        currNode = newNode; 
        length++; 
        lastC = currNode; 
       } 

      } 

     } 
     return this; 

    } 

    // Append char array c to the end of the current MyStringBuilder, and 
    // return the current MyStringBuilder. Be careful for special cases! 
    public MyStringBuilder append(char [] c) 
    { 
     if (c == null || c.length == 0) // Special case for empty char array 
     {         // or null reference 
      throw new NullPointerException("attempting to add empty character array"); 
     } 
     else 
     { 

      if (isEmpty()) // if stringbuilder is empty 
      { 
       // Create front node to get started 
       firstC = new CNode(c[0]); 
       length = 1; 
       CNode currNode = firstC; 

       // Create remaining nodes, copying from char array. 
       for (int i = 1; i < c.length; i++) 
       { 
        CNode newNode = new CNode(c[i]); 
        currNode.next = newNode; 
        currNode = newNode; 
        length++; 
        lastC = currNode; 
       } 
      } 
      //is stringbuilder is not empty 
      else { 
       CNode currNode = lastC; 
       //if string builder is not empty 
       // Create nodes, copying from char array. 
       for (int i = 0; i < c.length; i++) { 
        CNode newNode = new CNode(c[i]); 
        currNode.next = newNode; 
        currNode = newNode; 
        length++; 
        lastC = currNode; 
       } 

      } 

     } 
     return this; 
    } 

    // Append char c to the end of the current MyStringBuilder, and 
    // return the current MyStringBuilder. Be careful for special cases! 
    public MyStringBuilder append(char c) 
    { 
     CNode newNode = new CNode(c); 
     if (isEmpty()) 
     { 
      firstC = newNode; 
      lastC = newNode; 
     } //if stringbuilder object is empty 
     else 
     { 
      CNode currNode = lastC; 
      currNode.next=newNode; 
      currNode = newNode; 
      lastC = currNode; 
     } // if stringbuilder object is not empty 
     length++; 
     return this; 
    } 
public String toString() //!!must change to eliminate +!! 
    { 
     CNode currNode= firstC; 
     char [] temp = new char [length]; 
     int counter=0; 
     if (length == 0) 
      return ""; 
     while (currNode.next !=null) 
     { 
      temp[counter]=currNode.data; 
      currNode = currNode.next; 
      counter++; 
     } 
     temp[counter]=currNode.data; 
     String result = new String (temp); 
     return result; 
    } 


    /** additional private methods **/ 
    private boolean isEmpty() 
    { 
     if (length<1) 
      return true; 
     return false; 

    } //end of isEmpty 

private class CNode 
    { 
     private char data; 
     private CNode next; 

     public CNode(char c) 
     { 
      data = c; 
      next = null; 
     } 

     public CNode(char c, CNode n) 
     { 
      data = c; 
      next = n; 
     } 
    } // end of CNode inner class 
} //end of MyStringBuilder class 

ТЕСТ ВОДИТЕЛЯ ПРОГРАММА ASSIG2AltTest

public class Assig2AltTest 
{ 
    public static void main(String [] args) 
    { 
     System.out.println("Testing constructor methods"); 
     MyStringBuilder b1 = new MyStringBuilder("this is a string"); 
     char [] c = {' ','a','n','o','t','h','e','r',' ','s','t','r','i','n','g'}; 
     MyStringBuilder b2 = new MyStringBuilder(c); 
     MyStringBuilder b3 = new MyStringBuilder(); 

     System.out.println(b1); 
     System.out.println(b2); 
     System.out.println(b3); // will show as an empty line 

     System.out.println("\nTesting Append methods"); 
     b1.append(b2); 
     System.out.println(b1); 
     b1.append(" and another"); 
     System.out.println(b1); 
     b1.append(c); 
     System.out.println(b1); 
     b1.append('!'); b1.append('!'); // char append 
     b2.append(" different strings?"); 
     System.out.println(b1); // Testing for independence of the StringBuilders 
     System.out.println(b2); // after append. b1 should be unchanged here 
     // Special case appending to empty object 
     b3.append("...appending data"); 
     System.out.println(b3); 
    } 
} 
+1

Добро пожаловать на переполнение стека! См. [Как спросить] (http://stackoverflow.com/help/how-to-ask) и [Минимальный, полный и проверенный пример] (http://stackoverflow.com/help/mcve). – radoh

+0

Репетитор узнал, что/как использовать отладчик? – redFIVE

+1

Это простая отладка. Код выглядит не сложным, просто отлаживайте код за строкой и наблюдайте значения в окне просмотра. –

ответ

0

Проблема заключается в методе

public MyStringBuilder append(MyStringBuilder b) 

в классе MyStringBuilder

другой блок неправильно

} else {// works 
    CNode currNode = lastC; 

    CNode newNode = b.firstC; 
    for (int i = 1; i < b.length + 1; i++) { 
     currNode.next = newNode; 

     currNode = newNode; 

     newNode = currNode.next; 

     length++; 
    } 
    lastC = currNode; 
} 

этот код делает следующее - узел в этом теперь указывает на узел в b. Это означает, что когда вы добавляете в b2 в свой тест Assig2AltTest, вы фактически изменяете b1, так как b1 начали указывать на узлы от b2.

Вы должны изменить способ append(MyStringBuilder b) как это:

public MyStringBuilder append(MyStringBuilder b) { 
     if (length == 0) { 
      firstC = new CNode(b.firstC.data); 
      length = 1; 
      CNode currNode = b.firstC; 
      for (int i = 1; i < b.length; i++) { 
       CNode newNode = new CNode(currNode.next.data); 
       currNode.next = newNode; 
       currNode = newNode; 
       length++; 
      } 
      lastC = currNode; 

     } else {// works 
      CNode currNode = lastC; 

      CNode bNode = b.firstC; 
      for (int i = 1; i < b.length + 1; i++) { 

       CNode newNode = new CNode(bNode.data); 
       currNode.next = newNode; 

       currNode = newNode; 

       newNode = currNode.next; 
       bNode = bNode.next; 
       length++; 
      } 
      lastC = currNode; 
     } 
     return b; 
    } 
+0

Большое спасибо @КрасимирСтоев! Это почти работает, за исключением того, что в строке между каждыми частями комбинированной строки при печати метода toString имеется 16 пустых пространств. 'code' это строка это строка (16 пробелов) и другая это строка (16 пробелов) и другая строка это строка (16 пробелов) и еще одна строка !! 'code' – robotscantdie

+0

Да, теперь я отредактирую свой ответ - вы должны добавить 'bNode = bNode.next;' в теле цикла for –

+0

Спасибо человеку. Я понимаю. – robotscantdie