簡體   English   中英

如何將二維數組從 CSV 文件導入 JTable

[英]How to import a 2D Array into a JTable from a CSV file

我正在嘗試通過將 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() class 中的這段代碼

        //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();

問題在這里:

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

TempDatabase 嘗試訪問不存在的位置。 您在 tempdatabase 中有 3 個元素 em ALL strings[]? 核實。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM