java - 尝试自动递增数据时获取 "ArrayIndexOutOfBoundsException"

标签 java

我遇到 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];

关于java - 尝试自动递增数据时获取 "ArrayIndexOutOfBoundsException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16227029/

相关文章:

java - 如何将第三位玩家添加到我的简单 Java 骰子游戏中?

java - 无法执行目标 org.springframework.boot :spring-boot-maven-plugin:1. 5.8.RELEASE:run

java - android可运行差异

java - 有没有办法从终端启动本地 Java IBM Liberty 服务器?

java - 错误 : incompatible types: char cannot be converted to char[] charValue = Input. charAt(0);

java - 如何使用注释处理器从 src/main/resources 读取文件?

java - 从Java到C的矩阵转置移植,类型不兼容的问题

java - Google 表格 API 错误

java - 如何使用 Hibernate @ColumnTransformer 加密 Postgres 中的列

java - 数据库表的名称,如 t1、t2、t3 等