Java 如何绘制阵列曲线和阵列列表?
我正在创建一个消费者和生产者曲线,每一个都有自己的类别。使用者有一个点数组,生产者有一个点数组列表。我需要创建一个方法来创建“图形”(consumerCurve和producerCurve)。在这些方法中,需要检查无效参数(即没有负数),实例化数组/数组列表,然后实例化点/将它们存储在正确的插槽中。以下是我为消费者服务所做的:Java 如何绘制阵列曲线和阵列列表?,java,Java,我正在创建一个消费者和生产者曲线,每一个都有自己的类别。使用者有一个点数组,生产者有一个点数组列表。我需要创建一个方法来创建“图形”(consumerCurve和producerCurve)。在这些方法中,需要检查无效参数(即没有负数),实例化数组/数组列表,然后实例化点/将它们存储在正确的插槽中。以下是我为消费者服务所做的: public class ConsumerCurve { private Point[] myConsumerCurve; public void Curve() {
public class ConsumerCurve {
private Point[] myConsumerCurve;
public void Curve()
{
myConsumerCurve = new Point[10];
for(int x=0; x<10; x++)
{
myConsumerCurve[x] = new Point(x,x);
}
}
public ConsumerCurve(int np, double m, double b, int dx)
{
//*1)check for invalid parameters
Point[] myConsumerCurve = new Point [np];
if ( np < 0) {
throw new IllegalArgumentException("'np' must not be negative");
}
//2) Instantiate array using size n
for(int i=0; i<np; i++)
{
int x = i*dx;
double y = m*x+b;
myConsumerCurve[i] = new Point (x,y);
}
//3*)instantiate points store in correct slots
}
公共类消费者服务{
私用点[]美康曲线;
公共空隙曲线()
{
myConsumerCurve=新点[10];
对于(int x=0;x代码的一些注释:
Point[] myCurve = new Point [np]; // if np is negative here, you will get an exception
if( np< 0) {
np= -1;
}
如有必要,其他参数也是如此
如果Point
是java.awt.Point
,那么它的构造函数是Point(int,int)
-您必须将double
转换为int
:新的点(x,(int)y)
。如果Point
是您自己的类,在构造函数中接受double
,那么就可以了
最后,与其将点存储到局部变量myCurve
,不如像在curve()
方法中那样将它们直接存储在myConsumerCurve
中
myConsumerCurve = new Point [np];
for(int i=0; i<np; i++) {
int x = i*dx;
double y = m*x+b;
myConsumerCurve[i] = new Point (x, y); // or 'new Point (x, (int) y)' if it's java.awt.Point
}
myConsumerCurve=新点[np];
对于(int i=0;iYou已经在检查np<0
),只需以相同的方式检查其他参数。如果参数无效,会发生什么情况?np=(整数)null;
不起作用-您不能将null
分配给基元类型int
。在这种情况下,您可能应该抛出IllegalArgumentException
。将点存储在正确的插槽中是什么意思?您已经创建了数组myCurve
及其所有元素,也许您希望将其作为instance字段而不是局部变量?目前插槽中没有任何内容,因为在另一个类中,正在创建点,然后将点存储到插槽中以创建曲线。本质上,我需要让它说点是按顺序存储的(因此(0,0)(1,1)等)在插槽中,插槽具体是什么以及它们在哪里声明?您已经在此方法中创建了点,并且它们当前由x
排序。您只想将它们存储在其他位置吗?让我用更新的代码编辑我的问题,这应该会有所帮助。我刚刚编辑了我的代码,我不能让构造函数为空,这样就可以更改我需要创建一个for循环,搜索数组中的点是什么,如果一个点是负数,那么就说你不能有一个negativeConstructors没有返回类型,它们必须与类同名。如果你想consumerCurve()
若要成为构造函数,请将其声明为公共ConsumerCurve(…)
。我说了之后才意识到这一点。我如何创建一个for循环,通过数组查找负数,如果找到负数,它就会说不能有一个negative@retrogirl19检查其他参数的方法与检查np
的方法相同。如果没有一个参数是负数,那么x
y
be。在参数检查后,也移动Point[]myConsumerCurve=new Point[np];
,如答案中所述。
myConsumerCurve = new Point [np];
for(int i=0; i<np; i++) {
int x = i*dx;
double y = m*x+b;
myConsumerCurve[i] = new Point (x, y); // or 'new Point (x, (int) y)' if it's java.awt.Point
}