[英]Class inside a class java?
我正在做一个问题,要求您成为一个类客户,该客户以后将被添加到另一个类的方法中的数组列表中。 但是,我在标记为ERROR的行上收到一条错误消息,内容为:“无法访问类型为Question3的封闭实例。必须使用类型为Question3的封闭实例来限定分配(例如xxnew 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;
}
}
}
主要方法是静态的,因此具有静态上下文。 线程进入该代码块不需要Question3.class实例。 您的班级客户是在Question3中定义的。 因为它是一个内部类,所以它可以隐式访问Question3类内部的字段和方法,但是它需要Question3的实例才能实现该行为。 您需要将main(String args [])中现在拥有的代码移到Question3类的构造函数中,并在main方法中创建Question3的实例,如下所示:
public static void main(String args[]) {
Question3 myQuestion3 = new Question3();
}
或者,正如其他人提到的那样,您可以使客户类为静态。 这将通过有效地使客户成为顶级类来解决该问题,但是您将无法隐式访问其封闭类型(即Question3类)的字段和方法。
您还必须将kbd变量初始化为:
kbd =新的Scanner(System.in);
请使用此建议和上面的其他建议来查看您的代码。
首先,到目前为止,做得很好。 但是,我在代码中看到了几个错误。
首先,您的课程应该是静态课程。 您正在尝试使用没有静态类的静态方法。
public static class Question3 {
static ArrayList<customers> a= new ArrayList<customers>();
private static Scanner kbd;
public static void main(String[] args)
{
另外,您需要创建扫描仪供用户输入对象。
private static Scanner kbd = new Scanner(System.In);
做到这些,您的代码将完美运行!
您应该更改类customers
的声明以解决此问题。 当前是一个非静态内部类。 您应该将其更改为静态内部类。
public static class customers
非静态内部类隐式引用了容器类的实例。 在这里,您尝试在静态函数中创建customer
类的新实例,但那里没有Question3
实例。
只需将您的内部类更改为公共静态类:
public static class customers {
错误消失了:)
您的代码中有两个问题。 首先,您必须通过为其提供System.in参数来初始化扫描程序对象。 其次,在创建客户对象时,您必须遵循正确的语法。 这是工作代码:
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;
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.