2016-03-19 11 views
0

Bu yüzden hayvanların listesini oluşturan bir program oluşturmam gerekiyor. Program onları isimlerine göre ayırır ve alfabetik olarak listeye koyar. Ama "Hayvanı Görüntüle" düğmesine tıkladığımda, hiçbir şey göstermiyor, list.size() ile ilgili bir sorun olduğunu anladım, bu yüzden onu test etmek için tamsayı 10'a değiştirdim, ancak görüntülenen yalnızca ilk hayvanı gösterir.LinkedOrderedList ve LinkedList uygulaması

package animal; 
/** 
* @author Sharon Umute 
* Comp 139 001B 
* @param <T> 
*/ 
public class LinkedOrderedList<T> extends LinkedList<T> implements OrderedListADT<T>{ 


    /** 
    * Creates an empty list. 
    */ 
    public LinkedOrderedList() 
    { 
     super(); 
    } 

    /** 
    * Adds the specified element to this list at the proper location 
    * 
    * @param element the element to be added to this list 
    */ 
    @Override 
    public void add(T element) { 
     SinglyLinkedNode<T> node =new SinglyLinkedNode<>(element); 
     SinglyLinkedNode<T> previous=null; 
     SinglyLinkedNode<T> current=head; 
     Animal animal; 
     Animal animal2; 
     int result; 
     if(isEmpty()){ 
      tail = head = node; 
     }else{ 
      int i=0; 
      while(i<this.size()){ 
       animal=(Animal) current.getElement(); 
       animal2=(Animal) node.getElement(); 
       result=animal.getName().compareTo(animal2.getName()); 
       if((result==-1)&&(current!=head)&&(current!=tail)){ 
        previous=current; 
        current=current.getNext(); 
        i++; 
       }else if((result==1)&&(current!=head)&&(current!=tail)){ 
        previous.setNext(node); 
       }else if((result==0)&&(current!=head)&&(current!=tail)){ 
        i++; 
       } 
       if((current==head)||((size()==1)&&(result==1))){ 
        node.setNext(head); 
        head=node; 
       }else if((current==tail)||((size()==1)&&(result==-1))){ 
        tail.setNext(node); 
        tail=node; 
       } 
      } 
     } 
    } 
} 
:

Bu LinkeList sınıf

package animal; 
import exceptions.ElementNotFoundException; 
import exceptions.EmptyCollectionException; 
import java.util.*; 

/** 
* @author Sharon Umute 
* Comp 139 001B 
* @param <T> 
*/ 
public class LinkedList<T> implements ListADT<T> { 

protected int count; 
protected SinglyLinkedNode head, tail; 
protected int modCount; 

/** 
* The LinkedList constructor creates an empty list 
*/ 
public LinkedList(){ 
    count=0; 
    head=tail=null; 
    modCount = 0; 
} 
/** 
* Removes and returns the head element from this list. 
* 
* @return the head element from this list 
*/ 
@Override 
public T removeFirst() throws EmptyCollectionException { 
    if(isEmpty()){ 
     throw new EmptyCollectionException("list"); 
    } 

    T result=(T) head.getElement(); 
    head=head.getNext(); 
    count--; 
    modCount++; 
    return result; 
} 

/** 
* Removes and returns the tail element from this list. 
* 
* @return the tail element from this list 
*/ 
@Override 
public T removeLast() throws EmptyCollectionException { 
    if(isEmpty()){ 
     throw new EmptyCollectionException("list"); 
    } 

    T result=(T) tail.getElement(); 
    tail=tail.getNext(); 
    count--; 
    modCount++; 
    return result; 
} 

/** 
* Removes and returns the specified element from this list. 
* 
* @param targetElement the target element 
* @return the target element 
*/ 
@Override 
public T remove(T targetElement) throws EmptyCollectionException, ElementNotFoundException { 
    if(isEmpty()){ 
     throw new EmptyCollectionException("list"); 
    } 

    boolean found = false; 
    SinglyLinkedNode<T> previous = null; 
    SinglyLinkedNode<T> current = head; 

    while (current != null && !found) 
     if (targetElement.equals(current.getElement())) 
      found = true; 
     else 
     { 
      previous = current; 
      current = current.getNext(); 
     } 

    if (!found) 
     throw new ElementNotFoundException("LinkedList"); 

    if (size() == 1) // only one element in the list 
     head = tail = null; 
    else if (current.equals(head)) // target is at the head 
     head = current.getNext(); 
    else if (current.equals(tail)) // target is at the tail 
    { 
     tail = previous; 
     tail.setNext(null); 
    } 
    else // target is in the middle 
     previous.setNext(current.getNext()); 

    count--; 
    modCount++; 
    return current.getElement(); 


} 

/** 
* Returns a reference to the head element in this list. 
* 
* @return a reference to the head element in this list 
*/ 
@Override 
public T first() throws EmptyCollectionException { 
    if(isEmpty()){ 
     throw new EmptyCollectionException("list"); 
    } 

    T result=(T) head.getElement(); 
    return result; 
} 

/** 
* Returns a reference to the tail element in this list. 
* 
* @return a reference to the tail element in this list 
*/ 
@Override 
public T last() throws EmptyCollectionException { 
    if(isEmpty()){ 
     throw new EmptyCollectionException("list"); 
    } 

    T result=(T) tail.getElement(); 
    return result; 
} 

/** 
* Returns true if this list contains the specified target element. 
* 
* @param target the target that is being sought in the list 
* @return true if the list contains this element 
*/ 
@Override 
public boolean contains(T target) throws EmptyCollectionException { 
    if(isEmpty()){ 
     throw new EmptyCollectionException("list"); 
    } 
    for(T result:this){ 
     if(result.equals(target)){ 
      return true; 
     } 
    } 
    return false; 
} 

/** 
* Returns true if this list contains no elements. 
* 
* @return true if this list contains no elements 
*/ 
@Override 
public boolean isEmpty() { 
    return(head==null); 
} 

/** 
* Returns the number of elements in this list. 
* 
* @return the integer representation of number of elements in this list 
*/ 
@Override 
public int size() { 
    return count; 
} 

/** 
* Returns an iterator for the elements in this list. 
* 
* @return an iterator over the elements in this list 
*/ 
@Override 
public Iterator<T> iterator() { 
    return new LinkedListIterator(); 
} 


private class LinkedListIterator implements Iterator<T> 
    { 
     private int iteratorModCount; // the number of elements in the collection 
     private SinglyLinkedNode<T> current; // the current position 


    /** 
    * Sets up this iterator using the specified items. 
    * 
    * @param collection the collection the iterator will move over 
    * @param size  the integer size of the collection 
    */ 
    public LinkedListIterator() 
    { 
     current = head; 
     iteratorModCount = modCount; 
    } 

    /** 
    * Returns true if this iterator has at least one more element 
    * to deliver in the iteration. 
    * 
    * @return true if this iterator has at least one more element to deliver 
    *   in the iteration 
    * @throws ConcurrentModificationException if the collection has changed 
    *   while the iterator is in use 
    */ 
    public boolean hasNext() throws ConcurrentModificationException 
    { 
     if (iteratorModCount != modCount) 
      throw new ConcurrentModificationException(); 

     return (current != null); 
    } 

    /** 
    * Returns the next element in the iteration. If there are no 
    * more elements in this iteration, a NoSuchElementException is 
    * thrown. 
    * 
    * @return the next element in the iteration 
    * @throws NoSuchElementException if the iterator is empty 
    */ 
    public T next() throws ConcurrentModificationException 
    { 
     if (!hasNext()) 
      throw new NoSuchElementException(); 

     T result = current.getElement(); 
     current = current.getNext(); 
     return result; 
    } 

    /** 
    * The remove operation is not supported. 
    * 
    * @throws UnsupportedOperationException if the remove operation is called 
    */ 
    public void remove() throws UnsupportedOperationException 
    { 
     throw new UnsupportedOperationException(); 
    } 
} 

} 

Bu LinkedOrderedList sınıfı edilir: Ben sorun geliyor ve gerçekten kafam karıştı nerede emin değilim, burada kod bu

@Override 
    public void actionPerformed(ActionEvent ev) throws NullPointerException { 
    Object object = ev.getSource(); 
     if (object == addReptileButton) { 
      try { 
       useA= new Reptile(namePanel.getText(), weightPanel.getValue(), 
         agePanel.getValue(),reptileLengthPanel.getValue()); 
      } catch (InvalidNameException | InvalidWeightException ex) { 
       Logger.getLogger(SimpleGUI.class.getName()).log(Level.SEVERE, 
         null, ex); 
      } 

      try{ 
       list.add(useA); 
      }catch(EmptyCollectionException|NullPointerException ec){ 
       JOptionPane.showMessageDialog(null, "The List isEmpty", 
         "Input Error", 
        JOptionPane.ERROR_MESSAGE); 
      } 
     }else if (object == addMammalButton) { 
      try { 
       useA= new Mammal(namePanel.getText(), weightPanel.getValue(), 
         agePanel.getValue(),mammalColorPanel.getText()); 
      } catch (InvalidNameException | InvalidWeightException ex) { 
       Logger.getLogger(SimpleGUI.class.getName()).log(Level.SEVERE, 
         null, ex); 
      } 
      try{ 
       list.add(useA); 
      }catch(EmptyCollectionException|NullPointerException ec){ 
       JOptionPane.showMessageDialog(null, "The List is Empty", 
         "Input Error", 
        JOptionPane.ERROR_MESSAGE); 
      } 
     }else if (object == RemoveFirst) { 
      try{ 
       Animal current = (Animal) list.removeFirst(); 
      }catch(EmptyCollectionException|NullPointerException ec){ 
       JOptionPane.showMessageDialog(null, "The List is Empty", 
         "Input Error", 
        JOptionPane.ERROR_MESSAGE); 
      } 
     }else if (object == RemoveLast) { 
      try{ 
       Animal current = (Animal) list.removeLast(); 
      }catch(EmptyCollectionException|NullPointerException ec){ 
       JOptionPane.showMessageDialog(null, "The list is Empty", 
         "Input Error", 
        JOptionPane.ERROR_MESSAGE); 
      } 
     } else if (object == displayAnimalsButton) { 
      verifyArea.setText(" "); 
      try{ 
       for(int j=0; j<10; j++){ 
        Animal result = (Animal) list.removeFirst(); 
        verifyArea.append(result.toString()); 
        list.add(result); 
       } 
      }catch(EmptyCollectionException ex){ 
       verifyArea.append(" "); 
      } 
     } 

    } 
:

Bu SimpleGUI denilen GUI i Yani gösteren sadece o kısmın actionPerformed haricinde şey burada değiştirmek izin yok

Birisi bana sorunun ne olduğunu ve nasıl düzeltileceğini söyler. Bunu gerçekten takdir ediyorum.

+1

Sanırım herkes bu kodun tamamını kullanmak istemeyecek gibi görünüyor. Ne yanlış gittiğini görmek için kodunuzu adım atmak için bir hata ayıklayıcı kullanmanızı öneririm. –

+0

"Bunu test etmek için 10 numaralı tamsayıya değiştirdim, ancak görüntülenen ilk hayvanı yalnızca gösterir". Kaç hayvan bekliyorsun? Bir bağlantılı liste listesi 'n' hayvanı ekleyebilir ve nerede yanlış gittiğinizi görebilirsiniz. İşleminiz "Gösterge" yazdığında neden "removeFirst" dediğinizden emin değilsiniz. –

cevap

0

Sorununuzun nedeni bunun olup olmadığını bilmiyorum, ancak listeyi görüntüleme biçiminiz biraz çılgın. Her iki boyutun uygulamasında bir sorun varsa, ekleyin veya kaldırın, ardından listeyi görüntülemeye çalıştığınız her defasında çöp kutusuna atabilirsiniz.

Liste yineleyicisini kullanmak daha iyi bir yol olurdu.

Fakat daha genel olarak, IDE'nizde Hata Ayıklayıcısını nasıl kullanacağınızı öğrenmeniz gerekmiyor. Bir hata ayıklayıcısını kullanmak, her programcının ustalaşması gereken temel bir beceridir. Kod hatalarını ayıklayamayan bir programcı, temelde bir işverene işe yaramaz.

Öğrenmeniz gereken diğer şey, Birim Testlerinin nasıl yazılacağıdır.

+0

Teşekkürler, hata ayıklayıcısını nasıl kullanacağımı öğrenmem gerekiyor – Drew

İlgili konular