main函数为什么写在init()里面??奇怪

解决方案 »

  1.   

    真对不起,原程序拷过来时,忘了个括号:
    class Student
    {
    float math,english,sum;
    float f(float k1,float k2)
    {
    sum=k1*math+k2*english;
    return sum;
    }
    }
    public class Average
    {
      Student wanghong=new Student(),lihong=new Student();
      public void init()
         {
             wanghong.math=60.0f;
             wanghong.english=80.0f;
    lihong.math=70.0f;
    lihong.english=90.0f;
    wanghong.sum=wanghong.f(2.0f,2.0f);
    lihong.sum=lihong.f(2.0f,2.0f);
         }
        public static void main(String args[])
    {
               System.out.println("lihong sum="+lihong.sum);
      System.out.println("wnaghong sum="+wanghong.sum);
    }
    }
      这个程序提示:non-static variable lihong cannot be referenced from a static con text  
                     System.out.println("lihong sum="+lihong.sum);
                                                      ^
                     non-static variable lihong cannot be referenced from a static con text
                      System.out.println("wnaghong sum="+wanghong.sum);
                                                         ^
           这是什么意思啊,是哪里出错呢?
      

  2.   

    在main方法里面加上Average av=new Average();
      

  3.   

    在main方法里面加上Average av=new Average();还是不对,还是提示这两个错误啊!
      

  4.   

    wanghong ,lihong为非static变量
    要在static方法中引用,需用 对象.变量名
      

  5.   

    class Student
    {
    float math,english,sum;
    float f(float k1,float k2)
    {
    sum=k1*math+k2*english;
    return sum;
    }
    }
    public class Average{
     Student wanghong=new Student(),lihong=new Student();
    public void init(){
         wanghong.math=60.0f;
         wanghong.english=80.0f;
     lihong.math=70.0f;
     lihong.english=90.0f;
       wanghong.sum=wanghong.f(2.0f,2.0f);
     lihong.sum=lihong.f(2.0f,2.0f);    
    }
     public static void main(String args[])
    {  Average av=new Average();
       av.init();
          System.out.println("lihong sum="+av.lihong.sum);
      System.out.println("wnaghong sum="+av.wanghong.sum);
    }
    }
      

  6.   

    为什么要用av.init();这句呢?
    av.lihong.sum av.wanghong.sum这两句是对象引用对象,这样能行吗?
      

  7.   

    hi guys, your modification surely will solve the problem, but i think yxnk is asking about the key word STATICbasicly variables and methods declared as static belong to the class itself rather than a particular object ( Or you can think every object share the same static variable and method),and these static variables and methods are uniquely stored in the moemory. static objects will be initialized first whennever the class is accessed ( even though there is no object of this class is created yet).You cannot call a non-static method from a static method (but the reverse is ok), and you can call a static method for the class itself, whithout any object. Thats primarily what is static method for.