2014-12-05 61 views
2
import java.util.Scanner; 
import java.util.Arrays; 
import java.util.ArrayList; 

/** 
    This class prints the numeric value of a letter grade given by the user. 
*/ 
public class Words 
{ 
    int i=0; 
    String[] wordz; 
    /** 
     Constructs words class 
    */ 
    public Words() 
    { 
     wordz= new String[5]; 
    } 

    /** 
     collects 5 words from user and places then into array 
     @return the gradeValue 
    */ 
    public void inputArray(String a, String b, String c, String d, String e) 
    { 
     wordz = new String[] { a, b, c, d, e }; 
    } 

    /** 
     counts even and odds 
     @return numeric grade 
    */ 
    public void removeShortWords() 
    { 
     ArrayList<String> wordzList = new ArrayList<String>(Arrays.asList(wordz)); 
     for(i=0; i < wordz.length; i++) 
     { 

      if(wordz[i].length() < 3) 
       wordzList.remove(i);//out of bounds error here 

      String[] wordz = wordzList.toArray(new String[wordzList.size()]); 
     } 
    } 

    /** 
     prints out the array of 10 positive integers 
     @return numeric grade 
    */ 
    public void printArray() 
    { 
     System.out.println(Arrays.toString(wordz)); 
    } 
} 

這是我的測試人員類。字數組程序的出錯錯誤

import java.util.Scanner; 

public class WordPrgm { 

    public static void main(String[] args) 
    { 
     Words wordArray = new Words(); 
     System.out.println("PLease enter five words"); 
     Scanner in = new Scanner(System.in); 
     String w1 = in.nextLine(); 
     String w2 = in.nextLine(); 
     String w3 = in.nextLine(); 
     String w4 = in.nextLine(); 
     String w5 = in.nextLine(); 
     wordArray.inputArray(w1, w2, w3, w4, w5); 
     wordArray.removeShortWords(); 
     wordArray.printArray(); 
    } 
} 

這裏的程序應該從數組中刪除少於3個字母的單詞並打印出新單詞。我一直在一遍又一遍地查看代碼,但是我看不到解決方案在哪裏以及我錯過了什麼。我認爲for循環可能會搞砸了。謝謝!

我在程序的這一點上總是收到一個錯誤。

wordzList.remove(i); 
+0

少於五個?看起來更像我三個人。 – laune 2014-12-05 07:09:00

+0

是的,對不起,我沒有想到,它應該少於3,而不是5。 – javaProgrammer 2014-12-05 07:12:05

+0

@javaProgrammer如果答案幫助你不要忘記接受它 – 2014-12-19 07:40:23

回答

0
for(i=0; i < wordzList.size(); i++) 
{ 
    if(wordzList.get(i).length() < 3){ 
     wordzList.remove(i); 
     i--; 
    } 
} 
// Use the ArrayList from now on - so then next line is iffy. 
wordz = wordzList.toArray(new String[wordzList.size()]); 

問題從看陣列,同時在修改並行ArrayList的結果。一次只保留一個數據結構。

避免陣列 - ArrayLists提供更好的服務(如你所知),。

2
ArrayList<String> wordzList = new ArrayList<String>(Arrays.asList(wordz)); 
for(i=0; i < wordz.length; i++) 
{ 

    if(wordz[i].length() < 3) 
     wordzList.remove(i);//out of bounds error here 

    String[] wordz = wordzList.toArray(new String[wordzList.size()]); 
} 

讓我解釋你爲什麼會遇到問題。假設5個,2個和5箇中有2個詞的長度小於3.所以你必須從「wordzList」中刪除2個字符串。假設您刪除了第二個,現在列表大小爲4,最後一個可用值在索引3處。當您查找位於數組索引4的第五個字符串時,您試圖從列表中刪除不存在的元素。列出最後一個索引是3,但是您試圖刪除索引4處的元素。希望您在缺陷下工作。想想要克服的邏輯。

快樂編碼。

0

你會得到ArrayIndexOutOfBoundsException?嘗試檢查數組的維數。通常會拋出這個錯誤來表明一個數組已經被非法索引訪問......

+0

「通常」?是否有「異常」的情況下,這個例外將被拋出? – Tom 2014-12-05 08:37:12