如何修复Java中的ArrayIndexOutOfException错误?

时间:2019-04-25 06:39:07

标签: java arrays indexoutofboundsexception

我必须读取一个文件并将其存储到阵列中。我可以从文件中读取的最大数据量是数组大小20。我必须将文件上的内容存储到两个数组中。一种用于名称,另一种用于测试标记。我必须创建大小为20的String数组和Real大小为20的

问题:每当我为名称和标记创建大小为20的数组时,我都会不断获得

  

线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:   索引20超出长度20的范围

文件数据

Christopher Lee
54.0 
Stanley Wright
90.5
Oliver Stewart
75.8
Jessica Chang
34.65
Adam Bweon
66.60
Chrissy Yeo
88.9

由于我知道FILE中的数据,因此我尝试仅手动将ARRAY大小创建为6个数组,并且它可以工作。但是,每当我尝试使用FOR LOOP创建由6(已知)组成的数组时,它总是以ArrayIndexOutofExceptionError来打击我。

String[] array = new String[20];

//Using do while loop and catch the exception 

do {
    System.out.println("Please input the file name");
    name =sc.nextLine();
    // String[] array = new String[20];

    try {
        //Need to store Marks and Name seperately into an ARRAY
        File f = new File(name);
        BufferedReader br = new BufferedReader(new FileReader(f));
        String line = null;
        int i = 0; 

        while ((line = br.readLine()) != null) { /* If the readline is not null aka have something print LINE */
            array[i] = line;
            i++;            
        }
    } catch(FileNotFoundException e) { //When the file is not found it will show us the "PRINT"
        System.out.println("File can't be located");
    }
}

while(name.equals("")); //If the input doesnt equal to the correct name it will keep looping

String[] names = new String[6]; //Storing the names form the main ARRAY ^^
/*
    for(int i = 0; i < 6; i++)
    {
        for(int y = 0; y < 11; y += 2 )
        {
        names[i] = array[y];
        }
    }
    */

// Might have to double check with the number for the NULLEXCEPTION 
names[0] = array[0];
names[1] = array[2];
names[2] = array [4];
names[3] = array[6];
names[4] = array[8];
names[5] = array[10];

double[] marks = new double[6];
    /*
    for(int i = 0; i < 6; i++)
    {
        for(int y = 1; y <12; y += 2 )
        marks[i] =Double.parseDouble(array[y]);
    }
    */

marks[0] = Double.parseDouble(array[1]);
marks[1] = Double.parseDouble(array[3]);
marks[2] = Double.parseDouble(array[5]);
marks[3] = Double.parseDouble(array[7]);
marks[4] = Double.parseDouble(array[9]);
marks[5] = Double.parseDouble(array[11]);

    /*for(int i=1; i < 5; i++)
    {
        marks[i] = Double.parseDouble(array[i]);
        i++;
    }
    */

0 个答案:

没有答案