在下面的代码中,我添加了一些System.out.println语句,这样我每次都可以看到变量值的变化。但我现在遇到错误“令牌上的语法错误”println“,= expected”,虽然我检查了所有内容并且发现了任何错误。在添加那些System.out.println语句之前,一切正常。
这是我的代码:
public class A{
public static int temp = 4;
//System.out.println("temp = "+temp);
public int sum;
System.out.println("sum = " + sum);
public int y;
System.out.println("y = " + y);
public A(int x){
y = temp - 2 +x;
System.out.println("y = " + y);
sum = temp + 3;
System.out.println("sum = " + sum);
temp-=2;
//System.out.println("temp = "+temp);
}
public void methodB(int m, int n){
int x = 0;
y = y + m + (temp++);
System.out.println("y = " + y);
x = x + 2 + n;
System.out.println("x = " + x);
sum = sum + x + y;
System.out.println("sum = " + sum);
System.out.println(x + " " + y+ " " + sum);
}
}
class B extends A {
public int x;
public int sum;
System.out.println("sum = "+sum);
public B(int p){
super(p);
y = temp + p ;
System.out.println("y = "+y);
sum = p+ temp + 1;
System.out.println("sum = "+sum);
temp-=1;
}
public void methodB(int m, int n){
int y =0;
y = y + this.y;
System.out.println("y = " + y);
x = this.y + 2 + temp;
System.out.println("x = " + x);
super.methodB(x, y);
sum = x + y + super.sum;
System.out.println("sum = " + sum);
System.out.println(x + " " + y+ " " + sum);
}
}
class Test
{
public static void main(String [] args){
A a1 = new A(2);
B b1 = new B(3);
a1.methodB(1, 1);
b1.methodB(1, 2);
a1.methodB(3, 2);
b1.methodB(2, 2);
}
}
答案 0 :(得分:2)
您不能在方法之外使用print语句。在A级
System.out.println("temp = " + temp);
System.out.println("sum = " + sum);
System.out.println("y = " + y);
需要转移到方法中。在B级
System.out.println("sum = " + sum);
需要转移到方法中。
如果你想看看这些变量的默认值是什么,只需将这些print语句放在你的构造函数中,就像这样
public A(int x){
System.out.println("temp = " + temp);
System.out.println("sum = " + sum);
System.out.println("y = " + y);
y = temp - 2 + x;
System.out.println("y = " + y);
sum = temp + 3;
System.out.println("sum = " + sum);
temp -= 2;
//System.out.println("temp = " + temp);
}
答案 1 :(得分:0)
将System.out.println()
语句移至方法,可能是main
方法。它们不能在方法之外调用。