简体   繁体   中英

Null pointer exception Java 2d String

So I have a string[][] where I want to save some information from my database. Eclipse told me I needed to initialize my string[][], so i said string[]][] = null. Now I get a null pointer exception, but I'm not sure what I'm doing wrong.

try {
            Statement st = con.createStatement();
            String systems[][] = null;
            int firstcounter = 0;

            String item = "SELECT ram, cpu, mainboard, cases, gfx FROM computer_system";

            ResultSet rs = st.executeQuery(item);
            while (rs.next()){
                systems[firstcounter][0] = rs.getString("ram");
                systems[firstcounter][1] = rs.getString("cpu");
                systems[firstcounter][2] = rs.getString("mainboard");
                systems[firstcounter][3] = rs.getString("cases");
                systems[firstcounter][4] = rs.getString("gfx");
                firstcounter++;
            }
            System.out.println(systems[0][0]);

You are supposed to initialize the array to a non null value in order do use it :

String systems[][] = new String[n][5];

where n is the max capacity of the array.

If you don't know in advance how many rows your array should contain, you can use an ArrayList<String[]> instead, since the capacity of an ArrayList can grow.

For example:

        Statement st = con.createStatement();
        List<String[]> systems = new ArrayList<String[]>();
        String item = "SELECT ram, cpu, mainboard, cases, gfx FROM computer_system";
        ResultSet rs = st.executeQuery(item);
        while (rs.next()){
            String[] row = new String[5];
            row[0] = rs.getString("ram");
            row[1] = rs.getString("cpu");
            row[2] = rs.getString("mainboard");
            row[3] = rs.getString("cases");
            row[4] = rs.getString("gfx");
            systems.add(row);
        }

That's because, you initialize the systems[][] as null .

Try String systems[][] = new String[x][y]; instead, where x and y is the dimensions of your matrix.

But we do not like arrays in Java code, use Lists instead. Lists can expand dinamically, while your matrix can't, and Lists provide compile time type check, so it is more safe to use. For more info see Item 25 from Joshua Bloch's Effective Java , which says:

Item 25: Prefer lists to arrays

You need to initialize in following way

String systems[][] = new String[size][size];

where size = size of the string array you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM