0

我正在尝试通过 CSV 文件将文本文件数据库系统实现为 Java GUI,我已经创建了 GUI、数据库、导入和导出文件所需的方法以及将信息转换为 2DArray 的方法CSV 文件。我正在尝试创建一个简单的密码库,但是每当我尝试向文件中添加一些内容时,我都会收到一条错误消息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at TextFileDatabase.readDatabase(TextFileDatabase.java:93)
    at PasswordVault.<init>(PasswordVault.java:97)
    at PasswordVault.main(PasswordVault.java:22)

返回错误的方法是 readDatabase() 方法,如下所示:

public static String[][] readDatabase()
    {
        try
        {
            kb = new Scanner(database);
        }
        catch(FileNotFoundException e)
        {
            e.printStackTrace();
        }

        //since the size of the database is unknown, we'll first work in a temporary 2D arraylist that can dynamically change its size
        ArrayList<String[]> tempDatabase = new ArrayList<String[]>();

        while(kb.hasNext()) 
        {
            String tempLine = kb.nextLine(); //reads the first/next line of the database
            String[] tempData = tempLine.split(","); //gets that result as a string, splits it up into an array based on commas
            tempDatabase.add(tempData); //adds the string array to the arraylist
        }

        //at this point, the while loop should have traversed through the entire file

        String[][] output = new String[tempDatabase.size()][3];
            //this is the string we'll return
            //the column size is the size of the tempDatabase arraylist because thats the number of passwords we have stored
            //the row size is three because each row is an 1) app, 2) password, 3) description 

        //converts the ArrayList to the actual output array

        for(int x=0; x<output.length; x++)
        {
            for(int y=0; y<3; y++)
            {
                //This is line 93 in TextFileDatabase()
                output[x][y] = tempDatabase.get(x)[y];
            }
        }

        return output;
    }

它指向我 PasswordVault() 类中的这段代码

        //This is line 97
        String[][] data = TextFileDatabase.readDatabase();

        //This will convert the information from the 2DArray made from the file into a table model to use in the GUI 
        for(int a = 0; a < data.length; a++)
        {
            String[] row = new String[data[a].length];

            for(int b = 0; b < data[a].length; b++)
            {
                row[b] = data[a][b];
            }

            tableModel.addRow(row);
        }

错误调用的最后一行只是调用 PasswordVault() 构造函数的行

new PasswordVault();
4

1 回答 1

0

问题在这里:

output[x][y] = tempDatabase.get(x)[y];

TempDatabase 尝试访问不存在的位置。您在 tempdatabase 中有 3 个元素 em ALL strings[]?核实。

于 2020-04-03T13:32:07.507 回答