如何绘制数组和数组列表的曲线?

时间:2015-09-17 02:09:01

标签: java

我正在创建一个消费者和生产者曲线,每个曲线都是自己的类。消费者有一系列点,生产者有一个点数组列表。我需要创建一个方法来创建" graph" (consumerCurve和producerCurve)。在这些方法中,它需要检查无效参数(即没有负数),实例化数组/数组列表,然后实例化点/将它们存储在正确的槽中。以下是我对consumerCurve的看法:

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

}

我有第二部分,但我真的不知道如何检查invaid参数并在正确的位置获得积分。另外,数组列表是否相同?这可能是因为我看了这段代码的时间太长而且错过了它。

1 个答案:

答案 0 :(得分:0)

关于代码的几点评论:

Point[] myCurve = new Point [np]; // if np is negative here, you will get an exception
if( np< 0) {
    np= -1;
}

np中使用之前,您必须先检查new Point[np] ,否则在np为负的情况下会出现例外情况。将np设置为-1并不能解决问题。您应该将其设置为0,或者最好抛出一个异常,表明该参数是不可接受的:

if (np < 0) {
    throw new IllegalArgumentException("'np' must not be negative");
}

如有必要,其他参数也是如此。

如果Pointjava.awt.Point,则其构造函数为Point(int, int) - 您必须将double转换为intnew Point(x, (int) y) 。如果Point是你自己的类,它在构造函数中接受double,那就没关系。

最后,不是将点存储到局部变量myCurve,为什么不像myConsumerCurve方法那样直接将它们存储在curve()中?

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
}

另一方面,方法以小写字母开头(即curve(),而不是Curve())。