2014-12-05 64 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