Java 车牌厂
我在Java类中使用程序的概念时遇到了问题,它应该相对简单,但我发现很难 “编写生成许可证的类LicensePlateFactory 提供一个方法getNextPlate,返回一个唯一的 车牌号(整数)。对所有车辆使用序列号 由LicenseClateFactory创建的车牌,从 100001 编写一个创建LicensePlateFactory的程序,然后 从中获取并显示十几个连续的车牌。” 我的代码(看起来很糟糕,盯着问题看了一段时间后不知道该怎么办): 工厂:Java 车牌厂,java,Java,我在Java类中使用程序的概念时遇到了问题,它应该相对简单,但我发现很难 “编写生成许可证的类LicensePlateFactory 提供一个方法getNextPlate,返回一个唯一的 车牌号(整数)。对所有车辆使用序列号 由LicenseClateFactory创建的车牌,从 100001 编写一个创建LicensePlateFactory的程序,然后 从中获取并显示十几个连续的车牌。” 我的代码(看起来很糟糕,盯着问题看了一段时间后不知道该怎么办): 工厂: public class Li
public class LicensePlateFactory
{
private int k = 100001;
private int count;
public LicensePlateFactory(int x)
{
this.count++;
}
public static void main(String[] args)
{
getnextPlate();
}
public int getnextPlate()
{
return k + count;
}
}
public class LicensePlateFactoryRunner
{
private LicensePlateFactory fac;
public LicensePlateFactoryRunner()
{
for (int x = 1; x < 13; x++)
{
LicensePlateFactory fac = new LicensePlateFactory();
System.out.println(LicensePlateFactory.getnextPlate());
}
}
}
创建工厂的程序:
public class LicensePlateFactory
{
private int k = 100001;
private int count;
public LicensePlateFactory(int x)
{
this.count++;
}
public static void main(String[] args)
{
getnextPlate();
}
public int getnextPlate()
{
return k + count;
}
}
public class LicensePlateFactoryRunner
{
private LicensePlateFactory fac;
public LicensePlateFactoryRunner()
{
for (int x = 1; x < 13; x++)
{
LicensePlateFactory fac = new LicensePlateFactory();
System.out.println(LicensePlateFactory.getnextPlate());
}
}
}
公共类许可证PlateFactoryRunner
{
私人持牌工厂工厂;
公共许可证PlateFactoryRunner()
{
对于(int x=1;x<13;x++)
{
LicensePlateFactory fac=新的LicensePlateFactory();
System.out.println(LicensePlateFactory.getnextPlate());
}
}
}
也许我忘记了一些基本的java概念?您的代码将显示相同的车牌12次。原因是您正在为循环的每次迭代创建一个新的
LicensePlateFactory
。您应该做的是将工厂的创建移到循环之外
此外,这是一个小诡辩,但通常循环以0开头,除非你有很好的理由这样做。以下是一些提示:
PlateFactory
类:上次使用的车牌号和一个方法:getNextPlate()
返回一个plate
Plate
对象,该对象只有一个字段:Plate number,因为该对象在不使用工厂的情况下无法实例化(假定),因此它不应该有公共构造函数。我们还可以假设车牌号不能更改(最终字段,无设置器)main()
方法创建一个App
类,并在此方法中创建PlateFactory
实例,然后使用此实例12次以创建12个Plate
(编号100001、100002,…但由工厂处理)LicensePlateFactory
s?作业中说要创建12个牌照。这是作业,我会加上标签。我也让程序运行起来了,但我不确定它是否有效率。我将添加新代码。@用户:我知道您需要12个车牌。如果你在现实生活中需要12辆汽车,你需要建造12家工厂来制造它们吗?或者你需要一个工厂,然后你可以用它生产12辆汽车?