2015-12-02 2 views
1

Я пытаюсь просто вернуть сохраненные значения массива с помощью различных вызовов методов и значений подстроки и т. Д. В моем коде. Моя проблема в том, что в моем терминальном выходе - длина моего массива - одно значение, слишком большое по длине.Возвращаемая длина массива, хранящаяся в массиве

7 слов, которые хранятся в ArrayList

apple 
bannana 
peach 
plum 
orange 
lime 

5 слов, которые хранятся в ArrayList

apple 
peach 
plum 
lime 

Когда он должен выглядеть следующим образом:

6 слов, которые хранятся в a ArrayList

apple 
bannana 
peach 
plum 
orange 
lime 

4 слова, которые хранятся в ArrayList

apple 
peach 
plum 
lime 

Так что я пытаюсь выяснить, где я мог бы что-то отсутствует. Мой код выглядит следующим образом:

/** 
* Create an ArrayList<String> instance, and 
* assign it to wordList. 
*/ 
public Words() 
{ 
    this.wordList = new ArrayList<String>(); 
    populate(); 
} 

//  public ArrayList<String> getWordList() 
//  { 
//   return this.wordList; 
//  } 

/** 
* returns the size of wordList 
* 
* @return int 
*/ 
public int count() 
{ 
    return wordList.size()-1; 
} 

/** 
* Done 
*/ 
public void populate() 
{ 
    String[ ] spellings = 
     { 
      new String(""), 
      new String("1234"), 

      "a99le", 

      "apple",    
      "bannana", 
      "peach", 

      new String("plum"), 

      "orange", 
      "lime" 
     }; 

    for (String s: spellings) 
    { 
     this.addWord(s); 

    } 
} 

/* 
* Creates and returns a String[ ] array of all String elements 
* that are included in the wordList field. 
* 
* @return a String[ ] array 
*/ 
public String[ ] copyToWordArray() 
{ 
    String[]wordArray = new String[wordList.size()]; 

    for (int n = 0; n < wordArray.length; n++) 
    { 
     wordArray[n] = wordList.get(n); 
    } 
    return wordArray; 
} 

/* 
* Creates and returns an ArrayList of all String elements 
* in wordList that contain the given substring. 
* 
* @return ArrayList<String> 
* @param String substring 
*/ 
public ArrayList<String> contains(String substring) 
{ 
    ArrayList<String> list = new ArrayList<String>(); 
    for (String s: wordList) 
    { 
     if (s.contains(substring)) 
     { 
      list.add(s); 
     } 
    } 

    return list; 
} 

/* 
* Creates and returns an ArrayList of all String elements 
* in wordList that start with the given prefix. 
* 
* @return ArrayList<String> 
* @param String prefix 
*/ 
public ArrayList<String> startsWith(String prefix) 
{ 
    ArrayList<String> list = new ArrayList<String>(); 

    for (String s: wordList) 
    { 
     if (s.startsWith(prefix)) 
     { 
      list.add(s); 
     } 
    } 

    return list; 
} 

/** 
* Searches wordList with a for-each loop, and 
* returns the word if it is found. Otherwise, 
* returns null. 
* 
* @return String 
* @param String word 
*/ 
public String find(String word) 
{ 
    for (String s: wordList) 
    { 
     if (s.equals(word)) 
     { 
      return s; 
     } 
    } 
    return null; 
} 

/** 
* For a word to be valid: 
* 1) word.length() is postive, 
* 2) word contains alphabetic characters exclusively. 
*  
* This method uses a for loop to examine each character 
* in the given word. 
* 
* it returns: 
* - false for the first non-alphabetic character detected. 
* - true if all characters in the given word are strictly 
*  alphabetic, and the word length is positive. 
* 
* @return true or false 
* @param String str 
*/ 
private boolean isValidWord(String str) 
{ 
    if (str.length() > 0 && str!= null) 
    { 
     for (int i = 0; i < str.length(); i++) 
     { 
      if (!Character.isLetter(str.charAt(i))) 
      { 
       return false; 
      } 
     } 
    } 
    return true; 
} 

/** 
* Calls addWord(s) for each element s in the String[ ] array 
* to add them to wordList. 
* 
* @param String[ ] spellings 
*/ 
public void addWords(String[ ] spellings) 
{ 
    for (String s: spellings) 
    { 
     wordList.add(s); 
    } 
} 

/** 
* This method calls the find method to determine 
* whether the given word is already in wordList. 
* There are two cases: find returns either 
* 1) null -- word not found in wordList -- or 
* 2) the word -- the one that it found. 
* 

*  
* 
* 
* @param String word 
*/ 
public void add(String word) 
{ 
    String w = this.find(word); 

    if (w == null) 
    { 
     wordList.add(word); 

    } 
    return; 
} 

/** 
* If the given word is valid, this method calls the add(word) method. 
* 
* 
* @param String str 
*/ 
public void addWord(String str) 
{ 
    if (isValidWord(str)) 
    { 
     this.add(str); 
    } 

} 

/** 
* This method calls the find method. Two cases: 
* find returns either null or the word that was found. 
* 
* If the given word is found, the method removes 
* it from the wordList, 
*  
* 
* 
* @param String word 
*/ 
public void remove(String word) 
{ 
    String w = this.find(word); 

    if (w == null) 
    { 
     message = "The word cannot be removed from list."; 
    } 
    else 
    { 
     wordList.remove(word); 
    } 
} 

/** 
* This method, on the condition that there is an nth element 
* in wordList, removes the given word from the location. 
* 
* 
* @param n 
*/ 
public void remove(int n) 
{ 
    if (n < this.wordList.size()) 
    { 

     wordList.remove(n); 
    } 
} 

/** 
* Done 
*/ 
public String toString() 
{ 
    String str = wordList.size() + " words, stored in an ArrayList<String>"; 
    for (String c: wordList) 
    { 
     str += "\n\t" + c.toString(); 
    } 
    return str + "\n"; 
} 


/** 
* Done 
*/ 
public static void main(String[ ] args) 
{ 
    System.out.println(""); 
    Words words = new Words(); 

    System.out.println(words.toString()); 
    System.out.println(); 

    words.add("lemon"); 

    words.add("lemon"); 

    words.remove("lemon"); 

    words.remove("lemon"); 
    words.remove(words.count() - 1); 

    words.remove("bannana"); 

    System.out.println(words.toString()); 
    String[ ] wordArray = words.copyToWordArray(); 
    System.out.println(wordArray.length + " words, stored in a String[ ] array"); 
    for (String w: wordArray) 
    { 
     System.out.println("\t" + w.toString()); 
    } 
    System.out.println(); 

    ArrayList<String> list = words.contains("p"); 
    System.out.println(list.size() + " words that contain letter p"); 
    for (String w: list) 
    { 
     System.out.println("\t" + w.toString()); 
    } 
    System.out.println(); 

    list = words.startsWith("p"); 
    System.out.println(list.size() + " words that start with letter p"); 
    for (String w: list) 
    { 
     System.out.println("\t" + w.toString()); 
    } 
    System.out.println(); 
} 

}

Это, вероятно, что-то очень простое, что мне не хватает, но я не ловя - Спасибо заранее.

+0

'array.length' - твердый камень. Я сейчас смотрю на вашу гору кода, пытаясь подтвердить мое предположение, что вы заканчиваете пустую строку в начале или в конце вашего массива. –

+0

Вы провалили банан. –

ответ

1

Я думаю, что проблема может быть в методе addWords. Во всех ваших других методах add вы проверили, что строка, переданная в, действительна, но эта только добавляет строки непосредственно из переданного массива. Это метод, который используется, когда вы заполняете ArrayList в методе populate, вызываемом из конструктор.

Метод populate добавляет пустую строку в массив spellings, который добавляется в ArrayList. Если вы проверите правильность строк в массиве, переданном в addWords, эта пустая строка не будет добавлена ​​в ArrayList.

1

И это было быстрее, чем я думал. Как я и предполагал в своем комментарии, у вас есть пустая строка в вашем массиве. Обратите внимание в методе populate(), что первый String вы добавляете в свой внутренний список является

new String(""), 

, то есть пустая строка. Насколько я могу судить, вы никогда не удаляете его. Когда вы распечатываете содержимое, вы подсчитываете и печатаете этот элемент, но, по-видимому, его пропускаете, потому что соответствующий вывод принимает форму пустой строки.

Если вы поместите пустую строку где-то посредине списка, тогда вы увидите ее более легко. Кроме того, вы можете выводить кавычки вокруг своих слов или делать что-то другое, что позволяет отличать выходные слова от обычного пробела.

+0

Отлично. Я просто удалил пустую строку в методе populate(), и я получил желаемый результат. Должен ли я помещать пустые строки в другое место в будущем или не вставлять их в подобные методы? Спасибо. – Cassandra

+0

Вы должны использовать пустые строки везде, где это необходимо и, тем не менее, подходит. Ваша проблема, похоже, была не столько в использовании пустой строки, сколько в неправильной интерпретации вывода. Если пустая или пространственная строка должна быть разрешенным элементом, вам следует рассмотреть вывод кавычек вокруг каждого слова. В противном случае вам следует избегать добавления их или их добавления. –

0

Вы определяете свой счет как worList.size()-1, когда это должно быть только wordlist.size();

public int count() 
{ 
    return wordList.size()-1; 
} 
+0

count() используется только как индекс из слова List, поэтому size() - 1 дает индекс последней позиции. Однако, когда он используется в основном методе, он вызывает remove (count() - 1), поэтому на самом деле он удаляет второй последний элемент wordList. – ewanc

+0

Хорошо, возможно, ошибка, но определенно не основная причина. – phatfingers

+0

Согласен, определенно что-то заглянуть. Если ничто иное не вводит в заблуждение – ewanc

Смежные вопросы