ArrayIndexOutOfBoundsException无论我怎么努力

时间:2012-06-11 05:15:51

标签: java arrays

编辑:对于那些偶然发现这篇文章的人,我通过使用ArrayList而不是普通的数组来解决我的问题 - 这样做可以减少我的代码中的第三个并使其重复使用。感谢所有在下面帮助过的人。以下是我的更新代码的链接,供那些正在寻找的人使用:http://pastebin.com/Yh3LVu2H

该程序用于读取文件的行并将它们输出到两个数组xAxis和yAxis中 - iv将它分成两个文件,因为我将使用ScreenSizes.java构建GUI。

我在“System.out.println(”X:“+ xAxis [index]);”

这一行上获得了异常

ScreenSizes.java中的代码:

package screensizes;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class ScreenSizes{    

    public String filePath = "/Users/jonny/Documents/UNI/ScreenSizes/xy.txt";

    public static void main(String[] args) throws FileNotFoundException
    {
    ScreenSizes obj = new ScreenSizes();
        obj.run();
    }

    public void run() throws FileNotFoundException {
        GetScreens data = new GetScreens(filePath);
        int noLines = data.countLines();
        int[] xAxis = data.getData('x');
        int[] yAxis = data.getData('y');
    int index = 0;
        while(index<noLines){
        System.out.println("X: " + xAxis[index]);
        index++;
        }
    }
}

来自GetScreens.java的代码

package screensizes;
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;

public class GetScreens
{

    public int lines;
    public String filePath = "";
    public int[] x = new int[lines];    
    public int[] y = new int[lines];

    public GetScreens(String aFileName) throws FileNotFoundException{
        fFile = new File(aFileName);
        filePath = aFileName;
        try
        {
        processLineByLine();
        countLines();
        }
        catch(FileNotFoundException fnfe)
        {
            System.out.println(fnfe.getMessage());
        }
        catch(IOException ioe)
        {
            System.out.println(ioe.getMessage());
        }
    }

    public final void processLineByLine() throws FileNotFoundException {
        //Note that FileReader is used, not File, since File is not Closeable
        Scanner scanner = new Scanner(new FileReader(fFile));
        try {
            while ( scanner.hasNextLine() ){
                processLine( scanner.nextLine() );
            }
        }
        finally {
            //ensure the underlying stream is always closed
            //this only has any effect if the item passed to the Scanner
            //constructor implements Closeable (which it does in this case).
            scanner.close();
        }
    }

    public int[] getData(char choice){
        if(choice == 'x'){
            return x;
        }
        else{
            return y;
        }
    }

    public void processLine(String aLine){
        //use a second Scanner to parse the content of each line 
        Scanner scanner = new Scanner(aLine);
        scanner.useDelimiter("x");
        if ( scanner.hasNext() ){
           for(int i=0; i<lines; i++){            
                x[i] = scanner.nextInt();
                y[i] = scanner.nextInt();
           }
        }
        else {
            log("Empty or invalid line. Unable to process.");
        }
    }

    public int countLines(){
        try
        {
            BufferedReader reader = new BufferedReader(new FileReader(filePath));
            while (reader.readLine() != null) lines++;
            reader.close();
        }

        catch(FileNotFoundException fnfe)
        {
            System.out.println(fnfe.getMessage());
        }

        catch(IOException ioe)
        {
            System.out.println(ioe.getMessage());
        }
        return lines;
    }

    // PRIVATE 
    public final File fFile;

    private void log(Object aObject){
        System.out.println(String.valueOf(aObject));
    }

    private String quote(String aText){
        String QUOTE = "'";
        return QUOTE + aText + QUOTE;
    }
} 

5 个答案:

答案 0 :(得分:0)

您需要根据文件中的记录重新初始化int[] xint[] y

答案 1 :(得分:0)

GetScreens课程中,实例变量lines被隐式初始化为0。因此,您的xy数组的长度为零:没有元素。

因此,当您尝试在其他课程中使用它们时,您将获得ArrayIndexOutOfBoundsException

lines初始化为有用的内容。

编译程序时,请留意警告,例如:The variable _lines_ may not have been initialized

答案 2 :(得分:0)

public int[] x = new int[lines];    
public int[] y = new int[lines];

和以下一样好:

public int[] x = new int[0];    
public int[] y = new int[0];

在使用它们之前执行此操作:

x = new int[countLines()];    
y = new int[countLines()];

- V

答案 3 :(得分:0)

@Jonny

在您提供的processLine方法中

for(int i = 0; i&lt; lines; i ++)

{

            x[i] = scanner.nextInt();
            y[i] = scanner.nextInt();

}

但不明白你扫描的逻辑你不能扫描.nextInt()到x [i]和y [i]。在分配x [i]和y [i]是主要问题

使用

           x[i] = Integer.parseInt(scanner.next());

           y[i] = Integer.parseInt(scanner.next());

答案 4 :(得分:0)

如果必须使用数组,则必须首先使用countLines()计算行数,然后使用

初始化数组
 x = new int[lines];
 y = new int[lines];

然后你就可以开始处理......

结果如下:

public GetScreens(String aFileName) throws FileNotFoundException{
    fFile = new File(aFileName);
    filePath = aFileName;
    try
    {
        countLines();
        x = new int[lines];
        y = new int[lines];
        processLineByLine();
    } catch(FileNotFoundException fnfe) {
        System.out.println(fnfe.getMessage());
    }
    catch(IOException ioe) {
        System.out.println(ioe.getMessage());
    }
}

但是这个代码/设计很可能在以后使用时产生更多错误。我宁愿考虑为你的函数使用returnvalues。 (例如,如果你执行countLines()两次,你最终会得到你在该文件中实际拥有的两倍......

我认为使用ArrayList可以使您的代码更加安全。