预期的标识符?

时间:2015-04-27 05:17:41

标签: java symbols identifier

给出以下代码:

public class Test1 {
    int i;
    i = 4;
}   

public class Test2 {
    public static void main(String[] args) {
        Test1 t1 = new Test1();
        System.out.println(t1.i);
    }
}

为什么在尝试编译Test2时会得到以下内容?

./Test1.java:3: error: <identifier> expected
    i = 4;
     ^
./Test1.java:3: error: cannot find symbol
    i = 4;
    ^
  symbol:   class i
  location: class Test1
2 errors

2 个答案:

答案 0 :(得分:0)

您无法在班级主体中分配变量。试试这个:

public class Test1 {
    int i;
    {
        i = 4;
    }
}

作为替代方案,您可以在构造函数中或在setter方法中指定i

public class Test1 {
    int i;

    public Test1(int i) {
        this.i = i;
    }

    public void setI(int i) {
        this.i = i;
    }
}

答案 1 :(得分:0)

你在课堂上宣布“in​​t i”。您可以与声明一起分配或使用getter和setter。

line2user <- function(line, side) {
  lh <- par('cin')[2] * par('cex') * par('lheight')
  x_off <- diff(grconvertX(0:1, 'inches', 'user'))
  y_off <- diff(grconvertY(0:1, 'inches', 'user'))
  switch(side,
         `1` = par('usr')[3] - line * y_off * lh,
         `2` = par('usr')[1] - line * x_off * lh,
         `3` = par('usr')[4] + line * y_off * lh,
         `4` = par('usr')[2] + line * x_off * lh,
         stop("side must be 1, 2, 3, or 4", call.=FALSE))
}

OR

public class Test1 {
    int i = 4;
}