2014-09-01 170 views
0

我是一個Java新手,嘗試構建一個程序,該程序使用數據結構對給定文本文件的唯一字進行計數。爲了實踐,我自己實現了數據結構和抽象類。但是,當我運行該程序時,當涉及到add方法是MyArrayList時,我陷入了無限循環。繼續陷入無限循環(Java)

這種情況下的對象是一個SingleWord對象,由字符串字和整數計數組成,以跟蹤頻率。我沒有包括這個類在這裏創建對象。

public class MyArrayList<E> extends MyAbstractList<E> { 

    public static final int INITIAL_CAPACITY = 16; 
    private E[] data = (E[])new Object[INITIAL_CAPACITY]; 

    /** Create a default list */ 
    public MyArrayList() { 
    } 

    /** Create a list from an array of objects */ 
    public MyArrayList(E[] objects) { 
    for (int i = 0; i < objects.length; i++) 
     add(objects[i]); // Warning: don’t use super(objects)! 
    } 

    @Override /** Add a new element at the specified index */ 
    public void add(int index, E e) { 
    ensureCapacity(); 

    // Move the elements to the right after the specified index 
    for (int i = size - 1; i >= index; i--) 
     data[i + 1] = data[i]; 

    // Insert new element to data[index] 
    data[index] = e; 

    // Increase size by 1 
    size++; 
    } 

    /** Create a new larger array, double the current size + 1 */ 
    private void ensureCapacity() { 
    if (size >= data.length) { 
     E[] newData = (E[])(new Object[size * 2 + 1]); 
     System.arraycopy(data, 0, newData, 0, size); 
     data = newData; 
    } 
    } 

    @Override /** Clear the list */ 
    public void clear() { 
    data = (E[])new Object[INITIAL_CAPACITY]; 
    size = 0; 
    } 

    @Override /** Return true if this list contains the element */ 
    public boolean contains(E e) { 
    for (int i = 0; i < size; i++) 
     if (e.equals(data[i])) return true; 

    return false; 
    } 

    @Override /** Return the element at the specified index */ 
    public E get(int index) { 
    checkIndex(index); 
    return data[index]; 
    } 

    private void checkIndex(int index) { 
    if (index < 0 || index >= size) 
     throw new IndexOutOfBoundsException 
     ("index " + index + " out of bounds"); 
    } 

    @Override /** Return the index of the first matching element 
    * in this list. Return -1 if no match. */ 
    public int indexOf(E e) { 
    for (int i = 0; i < size; i++) 
     if (e.equals(data[i])) return i; 

    return -1; 
    } 

    @Override /** Return the index of the last matching element 
    * in this list. Return -1 if no match. */ 
    public int lastIndexOf(E e) { 
    for (int i = size - 1; i >= 0; i--) 
     if (e.equals(data[i])) return i; 

    return -1; 
    } 

    @Override /** Remove the element at the specified position 
    * in this list. Shift any subsequent elements to the left. 
    * Return the element that was removed from the list. */ 
    public E remove(int index) { 
    checkIndex(index); 

    E e = data[index]; 

    // Shift data to the left 
    for (int j = index; j < size - 1; j++) 
     data[j] = data[j + 1]; 

    data[size - 1] = null; // This element is now null 

    // Decrement size 
    size--; 

    return e; 
    } 

    @Override /** Replace the element at the specified position 
    * in this list with the specified element. */ 
    public E set(int index, E e) { 
    checkIndex(index); 
    E old = data[index]; 
    data[index] = e; 
    return old; 
    } 

    @Override 
    public String toString() { 
    StringBuilder result = new StringBuilder("["); 

    for (int i = 0; i < size; i++) { 
     result.append(data[i]); 
     if (i < size - 1) result.append(", "); 
    } 

    return result.toString() + "]"; 
    } 

    /** Trims the capacity to current size */ 
    public void trimToSize() { 
    if (size != data.length) { 
     E[] newData = (E[])(new Object[size]); 
     System.arraycopy(data, 0, newData, 0, size); 
     data = newData; 
    } // If size == capacity, no need to trim 
    } 

    @Override /** Override iterator() defined in Iterable */ 
    public java.util.Iterator<E> iterator() { 
    return new ArrayListIterator(); 
    } 


    private class ArrayListIterator 
     implements java.util.Iterator<E> { 
    private int current = 0; // Current index 

    @Override 
    public boolean hasNext() { 
     return (current < size); 
    } 

    @Override 
    public E next() { 
     return data[current++]; 
    } 

    @Override 
    public void remove() { 
     MyArrayList.this.remove(current); 
    } 
    } 

    public static StringWord compare(StringWord w1, StringWord w2, Comparator<StringWord> c) { 
     if(c.compare(w1.word,w2.word) > 0) 
      return w1; 
     else 
      return w2; 
    } 

} 

,這是我的抽象類

public abstract class MyAbstractList<E> implements MyList<E> { 
    protected int size = 0; // The size of the list 

    /** Create a default list */ 
    protected MyAbstractList() { 
    } 

    /** Create a list from an array of objects */ 
    protected MyAbstractList(E[] objects) { 
    for (int i = 0; i < objects.length; i++) 
     add(objects[i]); 
    } 

/** Add a new element at the end of this list */ 
    @Override 
    public void add(E e) { 
    add(size, e); 
    } 


    @Override /** Return true if this list contains no elements */ 
    public boolean isEmpty() { 
    return size == 0; 
    } 

    @Override /** Return the number of elements in this list */ 
    public int size() { 
    return size; 
    } 

    @Override /** Remove the first occurrence of the element e 
    * from this list. Shift any subsequent elements to the left. 
    * Return true if the element is removed. */ 
    public boolean remove(E e) { 
    if (indexOf(e) >= 0) { 
     remove(indexOf(e)); 
     return true; 
    } 
    else 
     return false; 
    } 
} 

,這是我的接口MYLIST

public interface MyList<E> extends java.lang.Iterable<E> { 
    /** Add a new element at the end of this list */ 
    public void add(E e); 

    /** Add a new element at the specified index in this list */ 
    public void add(int index, E e); 

    /** Clear the list */ 
    public void clear(); 

    /** Return true if this list contains the element */ 
    public boolean contains(E e); 

    /** Return the element from this list at the specified index */ 
    public E get(int index); 

    /** Return the index of the first matching element in this list. 
    * Return -1 if no match. */ 
    public int indexOf(E e); 

    /** Return true if this list contains no elements */ 
    public boolean isEmpty(); 

    /** Return the index of the last matching element in this list 
    * Return -1 if no match. */ 
    public int lastIndexOf(E e); 

    /** Remove the first occurrence of the element o from this list. 
    * Shift any subsequent elements to the left. 
    * Return true if the element is removed. */ 
    public boolean remove(E e); 

    /** Remove the element at the specified position in this list 
    * Shift any subsequent elements to the left. 
    * Return the element that was removed from the list. */ 
    public E remove(int index); 

    /** Replace the element at the specified position in this list 
    * with the specified element and returns the new set. */ 
    public Object set(int index, E e); 

    /** Return the number of elements in this list */ 
    public int size(); 

    /** Return an iterator for the list */ 
    public java.util.Iterator<E> iterator(); 
} 

主要方法等

import java.io.*; 
import java.util.*; 
import javax.swing.JOptionPane; 

public class DataStruc{ 
    public static void main(String[] args) throws Exception{ 
     boolean continueProcess = false; 
     Scanner input; 
     MyList<SingleWord> list = new MyArrayList<SingleWord>(); 

     //prompt user for input 
     do { 
      input = readFile(continueProcess).useDelimiter("[^A-Za-z]+"); 

      //process input(file) 
      while (input.hasNext()) { 
       list.add(new SingleWord(input.next())); 
      } 

      System.out.println(list); 

      //prompt user to continue input 
      int option = JOptionPane.showConfirmDialog(
          null, 
          "Continue opening file?", 
          "Select an Option", 
          JOptionPane.YES_NO_OPTION); 
      continueProcess = (option == 0)? true : false; 
     } while(continueProcess); 
    } 

    public static Scanner readFile(boolean continueProcess) throws Exception{ 
     String filename; 
     File file; 
     do { 
      filename = JOptionPane.showInputDialog("Enter file name:"); 
      file = new File(filename); 
      if (file.exists()) { //if file exist, process the file 
       System.out.println("\"" + filename + "\"" + " is found."); 
       continueProcess = false; 
      } else if (filename == null) { //if user click cancel 
       System.exit(0); 
      } else if(filename.length() == 0) { //if user click yes without entering any value 
       System.out.println("No file name has been entered."); 
       System.out.println("Please try again."); 
       continueProcess = true; 
      } 
      else{ //if the file does not exist 
       System.out.println("File " + 
            "\"" + filename + "\"" + 
            " does not exist"); 
       continueProcess = true; 
      } 
     } while(continueProcess); 

     return new Scanner(file); 
    } 

} 

類創建SingleWord對象

public class SingleWord{ 
    private int count = 1; 
    private String word; 

    public SingleWord(String word){ 
     this.word = word; 
    } 

    public String getWord() { 
     return word; 
    } 


    public int getCount() { 
    return count; 
    } 

    @Override 
    public String toString() { 
    return word; 
    } 
} 

對不起,謝謝你:'(

文本文件是在這裏:

的文章(以下簡稱藝術)是使用一個名詞,表示一個字(或前綴或後綴)名詞形式的參考類型。文章指定名詞的語法定義,在某些語言中擴展到數量或數量範圍。英文文章是和/或(某些情況下)一些。 'An'和'a'是古代英語'an'的現代形式,在盎格魯方言中,它是數字'one'(在撒克遜方言中'比較'),並以數字'ane'存活到現代蘇格蘭人中。 'on'(被諾曼人重寫爲'one')和'an'存活到現代英語中,其中'one'用作數字,'an'('a',以輔音開頭的名詞前)作爲無限期的文章。他們是「a」
+1

這是你的調試器非常擅長幫助你解決的問題。 – 2014-09-01 17:27:21

+0

構造函數public MyArrayList(E [] objects)''可以簡單地調用'super(objects);'而不是像超類構造函數那樣做。 – Tom 2014-09-01 17:29:24

+0

您不會向我們展示您的'main',輸入文本文件內容,代碼的其他部分以及它所在的循環的位置。所有這些缺少的部分使它(可能)無法幫助您。 – alfasin 2014-09-01 17:29:41

回答

5

這是因爲您的抽象類的add方法正在調用自己。

@Override 
public void add(E e) { 
    add(e); 
} 

我想你想要更多的東西一樣:

@Override 
public void add(E e) { 
    add(size, e); 
} 
+0

+1它不是'@ override'它是'@ Override'(大寫'O') – alfasin 2014-09-01 17:31:06

+0

感謝您對Override的錯字校正。 關於添加,關於我能讀的,我看到他正在調用add(e),而不是add()。 – 2014-09-01 17:33:04

+1

@alfasin該方法正在調用自己,除非他有另一個add方法和一個通用的參數。注意實現實際添加的方法有2個參數 – coffeeaddict 2014-09-01 17:33:37

0

Offcourse它的無限循環,你遞歸調用同樣的方法。你必須像這樣改變比較方法代碼塊:

public static SingleWord compare(SingleWord w1, SingleWord w2, Comparator<String> c) { 
    if (c.compare(w1.getWord(), w2.getWord()) > 0) { 
     return w1; 
    } else { 
     return w2; 
    } 
}