尝试自动增加数据时获取“ArrayIndexOutOfBoundsException”

时间:2013-04-26 00:47:12

标签: java

我遇到ArrayIndexOutOfBoundsException: 0错误,因为i等于0并且没有自动递增。如何修复此代码以使其按预期工作?

我希望它能自动增加用Arrays读取的文件中读取的每一行数据。无论我把i++;放在哪里,我都会遇到这个问题。如果我使用另一个变量:同样的问题。

import java.io.*;
import java.util.*;

public class IdolResults
{
    public static void main(String[] args) throws FileNotFoundException
    {

        //construct Scanner
        //Scanner in = new Scanner(System.in);
        Scanner in = new Scanner(new File("eleVotes1.txt"));
        Scanner in2 = new Scanner(new File("eleVotes2.txt"));

        String[][] array;
        int[][] array2;
        String[] nameArray;
        int[] voteArray;
        int i = 0;

        while (in.hasNextLine())
        {   
             String name = in.next();
             int vote = in.nextInt();

             System.out.println(name);
             System.out.println(vote);

             //stuffhere: print, save name and vote, etc..
             //create an array and save info there
             array = new String[i][];
             array2 = new int[i][];

             array[i][0] = name;
             array2[i][1] = vote;

             //individually store name and votes
             nameArray = new String[10];
             voteArray = new int[10];

             nameArray[i] = name;
             voteArray[i] = vote;
             i++;

        }
    }//end of main
}//end of class

我最终想要操纵这些存储的数据,所以我可以这样做: 预期产出:

Results for 2099
Idol Name        Votes Received    % of Total Votes
__________________________________________________      
Clarkson            80,000            14.4%
Seacrest            100,000           18.0%
Dunkleman           75,000            13.5%
Cowell              110,000           19.7%
Abdul               125,000           22.4%
Jackson             67,000            12.0%

Total Votes         557,000

The winner is Abdul!

1 个答案:

答案 0 :(得分:5)

这里

array = new String[i][];
array2 = new int[i][];

你只是实例化你的外部数组。你也必须实例化内部数组

所以

array[i] = new string[j];