尝试打印类变量时收到错误

时间:2013-12-04 13:39:01

标签: java

package mydate;

public class MyDate {

  private int day=1;
  private int month=1;
  private int year=2000;

public MyDate(int day,int month,int year)
{
  this.day=day;
  this.month=month;
  this.year=year;
  System.out.println(day+"  "+month+"  "+year);
}  
 System.out.println(day+"  "+month+"  "+year);// I am getting an error on this line saying cannot find symbol.How to print class variables of MyDate?

}

package mydate;

public class TestMyDate {

public static void main(String[] args) {
 MyDate today=new MyDate(22,7,1964); 
}
}

4 个答案:

答案 0 :(得分:2)

因为在一个类中你不能有一个print语句。仅限于功能!

答案 1 :(得分:1)

此行System.out.println(day+" "+month+" "+year);// I am getting an error on this line saying cannot find symbol. How to print class variables of MyDate?必须位于类或构造函数的方法中。你不能把它粘在类定义的任何地方。我会把它放在一个方法而不是一个构造函数中,如下所示:

例如:

 public void printDate() {
     System.out.println(day+"  "+month+"  "+year);// I am getting an error on this line saying cannot find symbol. How to print class variables of MyDate? 
 }

然后,在main()中,您可以在对象引用上调用该方法:

 MyDate today=new MyDate(22,7,1964);  
 today.printDate();

答案 2 :(得分:0)

你不能在课堂上有自由浮动的陈述。尝试类似:

public void printInfo() {
    System.out.println(day+"  "+month+"  "+year);
}

然后你可以做

MyDate today=new MyDate(22,7,1964);
today.printInfo();

答案 3 :(得分:0)

从Class.It中删除System.out.println将正常工作。