听起来很简单,但对我来说这很奇怪。我正在尝试导入一个数据文件(我已经成功完成),并使用它并比较每个单词以查看哪个单词最长。到目前为止,它不起作用(索引超出范围),当我确实操纵它(错误地)工作时,它给了我一个错误的单词作为最长的单词。
这是我目前所拥有的......
主文件:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import static java.lang.System.*;
public class FancyWordsRunner
{
private static int max = 0;
public static void main( String args[] ) throws IOException
{
ArrayList<String> wordList = new ArrayList<String>();
{
String ray = "";
Scanner welcome = new Scanner(new File("fancywords.dat"));
while(welcome.hasNext())
{
ray = welcome.next();
wordList.add(ray);
for(int i = 0; i<wordList.size(); i++)
{
int j = i+1;
if(wordList.get(j).length()>wordList.get(i).length())
max = j;
}
}
}
String maximum = wordList.get(max);
out.println(maximum);
}
}
花式字.dat:
2013 UIL STATE CONTEST
PROGRAMMING IS FUN
TODAY IS SATURDAY
电流输出:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at FancyWordsRunner.main(FancyWordsRunner.java:35)