您的位置:首页 > 编程语言 > Java开发

Java出现No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing

2017-03-09 23:43 591 查看
编译错误提示:No enclosing instance of type demo1_1 is accessible. Must qualify the allocation with an enclosing instance of type demo1_1 (e.g. x.new A() where x is an instance of demo1_1).

注:demo1_1是我的类名

提示信息是,没有可访问的内部类demo1_1的实例,必须分配一个合适的内部类demo1_1的实例(如x.new A(),x必须是demo1_1的实例。)看着这句提示,其实我已经用new实例化了这个类,为什么还不行呢。

问题原因:原来我写的内部类Dog是动态的,也就是开头以public class开头。而主程序是public static class main。在Java中,类中的静态方法不能直接调用动态方法。只有将某个内部类修饰为静态类,然后才能够在静态类中调用该类的成员变量与成员方法。

解决办法:将public class改为public static class.

附上源程序并标注了错误处:希望对大家有用

package Demo1;

import java.io.*;

public class demo1_1 {

 public static void main(String[] args) throws Exception

 {

    Dog dogs[]=new Dog[4];

  InputStreamReader isr=new InputStreamReader(System.in);

  BufferedReader br=new BufferedReader(isr);

  for(int i=0;i<4;i++)

  {

   dogs[i]=new Dog();

   System.out.println("请输入第"+(i+1)+"只狗名:");

   

    //从控制台读取狗名

    String name=br.readLine();//异常……

    

   //将名字赋给对象

   dogs[i].setName(name);

   System.out.println("请输入第"+(i+1)+"只狗的体重");

   String s_weight=br.readLine();

   float weight=Float.parseFloat(s_weight);//String转float

   //将体重赋给对象

   dogs[i].setWeight(weight);

  }

  

  //计算总体重

  float allWeight=0;

  for(int i=0;i<4;i++)

  {

   allWeight+=dogs[i].getWeight();

  }

  ////计算平均体重

  float avgWeight=allWeight/dogs.length;

  System.out.println("总体重:"+allWeight+"平均体重:"+avgWeight);

 }

 

 //定义一个狗类
 public class Dog//问题所在;改为: public static class Dog 就可以了 
 {

  private String name;

  private float weight;

  public String getName() {

   return name;

  }

  public void setName(String name) {

   this.name = name;

  }

  public float getWeight() {

   return weight;

  }

  public void setWeight(float weight) {

   this.weight = weight;

  }

  

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐