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);发布于 2014-12-05 16:05:12
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个单词的长度小于3,因此你必须从"wordzList“中删除2个字符串。假设您删除了第二个字符串,现在列表大小为4,最后一个可用值位于索引3。当您查找位于数组索引4的第5个字符串时,您正在尝试从列表中删除不存在的元素。列表的最后一个索引是3,但您正在尝试删除索引4处的元素。希望您在该缺陷下。想一想要克服的逻辑。
祝你编码愉快。
发布于 2014-12-05 15:07:36
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提供了更好的服务(正如你已经发现的)。
发布于 2014-12-05 16:27:15
你得到ArrayIndexOutOfBoundsException了吗?尝试检查数组的维数。这通常被抛出以指示数组已被非法索引访问...
https://stackoverflow.com/questions/27310547
复制相似问题