0

我有一个ArrayIndexOutOfBoundsException: 0错误,因为i等于0而不是自动递增。如何修复此代码以使其按预期工作?

我希望它自动增加使用数组读取的文件中读取的每一行数据。无论我把它放在哪里,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!
4

1 回答 1

5

这里

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

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

所以

array[i] = new string[j];
于 2013-04-26T00:50:09.967 回答