我出现了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!
最佳答案
这里
array = new String[i][];
array2 = new int[i][];
您只是实例化您的外部数组。您也必须实例化内部数组
所以
array[i] = new string[j];