yexaacs
Posts: 1
Joined: Wed Feb 27, 2019 5:53 am
Contact: Website

I want to initialize two dimensional array in constructor

Wed Feb 27, 2019 6:02 am

I want to initialize two dimensional array in constructor. But, I have a problem when I declare instance variable of array in class. It will be error if I make it like this:

Code: Select all

public class Data {
private String [][] tabel;
public Data(){
    tabel = {{"ID", "NAME"},
             {"101", "Max"},
             {"102", "Mark"},
             {"103", "Downey"},
             {"104", "Matthew"},
             {"105", "Richard"}};
}
How I can solve this problem in my java project?

knute
Posts: 428
Joined: Thu Oct 23, 2014 12:14 am
Location: Texas
Contact: Website

Re: I want to initialize two dimensional array in constructor

Wed Feb 27, 2019 9:41 pm

Code: Select all

public class test {
    private String[][] table;
    public test() {
        table = new String[][] {{"ID","NAME"},
            {"101","Max"},
            {"102","Mark"}};
    }

    public static void main(String... args) {
        test test = new test();
        for (int i=0; i<test.table.length; i++) {
            for (int j=0; j<test.table[0].length; j++) {
                System.out.print(test.table[i][j] + " ");
            }
            System.out.println();
        }
    }
}


Return to “Java”