简体   繁体   English

Java“表达式的非法开始”错误…如何解决此错误?

[英]Java “illegal start of expression” error…How to fix this error?

I was developing a program using NetBeans IDE and i got an error in front of a line saying 我正在使用NetBeans IDE开发程序,但在一行前面说了一个错误

illegal start of expression and below that written ';' 非法的表达开始,且写在下面; expected 预期

I am new to Java and I am unable to fix this error when I was assigning a value to an array. 我是Java新手,为数组分配值时无法修复此错误。

Below is a part of code where the error occured : 以下是发生错误的部分代码:


String[] colname;
   int j=0;
   while(rs.next()){
     for(int i=0;i<cols;i++){
       colname={dtm.getColumnName(i)};       //**<-- This is where the error occured**
                }
                    colName=colname;   //colName is also an array of String datatype.
                    Object[] value = {rs.getObject(colName[j])};
                    dtm.addRow(value);
                    j++;
                }

All apart the line 全线

colname={dtm.getColumnName(i)};

Does not give any error. 没有给出任何错误。 But the error occurs only in the above line. 但是错误仅发生在上面的行中。

I found myself unable to fix it. 我发现自己无法修复它。 Can anyone help me to fix it? 谁能帮我修复它?

You can't use that form of array creation when simply assigning to a variable - it's only valid as part of a variable declaration. 简单地分配给变量时,不能使用这种形式的数组创建-它仅在变量声明中有效。 You need: 你需要:

colname = new String[] { dtm.getColumnName(i) };

However, I don't think this actually does what you want it to... all but the last iteration of the loop will be pointless. 但是,我认为这实际上并没有达到您想要的目的……除了循环的最后一次迭代之外,其他一切都没有意义。

You probably want something more like: 您可能想要更多类似的东西:

String[] colNames = new String[cols];
for (int i = 0; i < cols; i++) {
    colNames[i] = dtm.getColumnName(i);
}

I would also strongly recommend that you avoid code like this: 我也强烈建议您避免使用以下代码:

 colName=colname;

Having two variables which differ only in case is a really bad idea. 有两个仅在大小写不同的变量是一个非常糟糕的主意。

You have 2 ways of initializing an array: 您有两种初始化数组的方法:

String[] colname= {dtm.getColumnName(i)};

or 要么

colname= new String[] {dtm.getColumnName(i)};

But you can't mix them. 但是你不能把它们混在一起。 In your case, you would use the latter because you don't have the information to populate it yet on the line where you declare it. 在您的情况下,您将使用后者,因为您还没有在声明它的行上填充它的信息。

Note however that this is probably not going to do what you want as you will keep reassigning a new array at each loop. 但是请注意,这可能不会做您想要的事情,因为您将在每个循环中不断重新分配一个新数组。 You could make your life easier by using an ArrayList instead: 您可以使用ArrayList来简化生活:

List<String> colName = new ArrayList<String> ();

//in your loop
colName.add(dtm.getColumnName(i));

You can read more about arrays in this tutorial . 您可以在本教程中阅读有关数组的更多信息。

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

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