简体   繁体   English

Java多维数组未正确填充

[英]Java multi-dimensional array is not populating correctly

I have declared a multi- dimensional array like this:我已经声明了一个多维数组,如下所示:

String[][] contentDetails  = {};    

I populated the array like this:我像这样填充了数组:

contentDetails[][]  = {{"Availability","Available from: "+empst}, 
                     {"Rate in EUR/Hour",rst.getString(25)}};

It is getting error.它正在出错。 How can I do that?我怎样才能做到这一点? I am new this.我是新来的。 Please help me.请帮我。

What I want is an empty array first and then need to populate!!我想要的是一个空数组,然后需要填充!!

This is because array constants can only be used in initializers.这是因为数组常量只能在初始化器中使用。

The following would work:以下将起作用:

 String[][] contentDetails  = {{"Availability","Available from: "+empst}, 
                                {"Rate in EUR/Hour", rst.getString(25)}};

If you don't want to fill it on instantiation you need to instantiate the array giving it the length for both dimensions like this:如果你不想在实例化时填充它,你需要实例化数组,给它两个维度的长度,如下所示:

String[][] contentDetails = new String [length1][length2]; String[][] contentDetails = new String [length1][length2];

where length1 and length2 are integers (int).其中,长度1长度2是整数(INT)。

You can only use Arrays constant when creating the array, not after.创建数组时只能使用Arrays 常量,之后不能使用。 It make sense because, how Java would know the size of the array when instantiating otherwise ?这是有道理的,因为 Java 在实例化时如何知道数组的大小?

So you can do this所以你可以这样做

String[][] contentDetails = {{"Availability","Available from: "+empst}, 
            {"Rate in EUR/Hour",rst.getString(25)}};

or declare the array then loop over it to set the values或声明数组然后循环它以设置值

String[][] contentDetails [2][2];

...

for(int i = 0;i<2;i++)
  for(int j = 0;j<2;j++)
    //set the value of contentDetails here

The correct syntax in Java looks like this: Java 中的正确语法如下所示:

String[][] contentDetails = new String[][] {
    new String[] { "Availability", "Available from: "+empst }, 
    new String[] { "Rate in EUR/Hour", rst.getString(25) }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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