有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java类中的类?

我在做一个问题,要求你创建一个类,这个类稍后将被添加到另一个类的方法中的数组列表中。然而,我在我标记的错误行上得到了一个错误,它说: “无法访问Question3类型的封闭实例。必须使用Question3类型的封闭实例限定分配(例如,x.new A(),其中x是Question3的实例)。”我不知道为什么

public class Question3 {

    static ArrayList<customers> a= new ArrayList<customers>();
    private static Scanner kbd;

    public static void main(String[] args)
    {
        String input="";
        double price=1;
        String name="";
        while(price != 0)
        {
            System.out.println("Customer Name: ");
            name= kbd.nextLine().trim();
            System.out.println("Purchase Price: ");
            price= Double.parseDouble(kbd.nextLine().trim());
            addSale(name,price);                    //ERROR
        }
    }
    public static void addSale(String name, double price)
    {
        customers c= new customers(name,price);
        a.add(c);
    }
    public class customers 
    {
        String name;
        double price;
        public customers(String name, double price)
        {
            this.name=name;
            this.price=price;
        }
    }
}

共 (3) 个答案

  1. # 1 楼答案

    代码中有两个问题。 首先,您必须通过提供系统来初始化扫描仪对象。与之相关的参数。 第二,在创建customer对象时,必须遵循正确的语法。 以下是工作代码:

    public class Question3 {
    
    static ArrayList<customers> a= new ArrayList<customers>();
    private static Scanner kbd=new Scanner(System.in);  // <---- Notice this 
    
    public static void main(String[] args)
    {
        String input="";
        double price=1;
        String name="";
        while(price != 0)
        {
            System.out.println("Customer Name: ");
            name= kbd.nextLine().trim();
            System.out.println("Purchase Price: ");
            price= Double.parseDouble(kbd.nextLine().trim());
            addSale(name,price);                    //ERROR
        }
        System.out.println(a);
    }
    public static void addSale(String name, double price)
    {
        // customers c= new customers(name,price);
        Question3.customers c = new Question3().new customers(name, price); // <---Notice this 
        a.add(c);
    }
    public class customers 
    {
        String name;
        double price;
        public customers(String name, double price)
        {
            this.name=name;
            this.price=price;
        }
    } }
    
  2. # 2 楼答案

    为了解决这个问题,您应该更改类customers的声明。 目前它是一个非静态的内部类。您应该将其更改为静态内部类

    public static class customers

    非静态内部类隐式引用容器类的实例。在这里,您试图在静态函数中创建customer类的新实例,但那里没有Question3实例

  3. # 3 楼答案

    主方法是静态的,因此具有静态上下文。没有问题3的例子。类是线程进入该代码块所必需的。问题3中定义了您的班级客户。因为它是一个内部类,所以它可以隐式访问Question3类内部的字段和方法,但它需要Question3的实例才能实现该行为。您需要将main中现有的代码(String args[])移动到Question3类的构造函数中,并在main方法中创建Question3的实例,如下所示:

    public static void main(String args[]) {
        Question3 myQuestion3 = new Question3();
    }
    

    或者,正如其他人所提到的,您可以将客户类设置为静态。这将通过有效地使客户成为顶级类来解决这个问题,但您将失去隐式访问其封闭类型(Question3类)的字段和方法的能力