对数螺旋

时间:2011-02-15 06:03:55

标签: java math

所以在我的编程课中,我们正在学习使用绘图类。基本上绘制一条线和东西,我们在课堂上做了y=mx+b行。

我想跳过去,开始做更疯狂的数学运算!

我在使用这个时遇到了麻烦,我在普林斯顿大学的网站上找到了它。

public class Spiral {

    public static void main(String[] args) { 
        int N         = Integer.parseInt(args[0]);     // # sides if decay = 1.0
        double decay  = Double.parseDouble(args[1]);   // decay factor

        double angle  = 360.0 / N;
        double step   = Math.sin(Math.toRadians(angle/2.0));
        Turtle turtle = new Turtle(0.5, 0.0, angle/2.0);
        for (int i = 0; i < 10*N; i++) {
            step /= decay; 
            turtle.goForward(step);
            turtle.turnLeft(angle);
        }

    }
} 

import java.awt.Color;

public class Turtle {
    private double x, y;     // turtle is at (x, y)
    private double angle;    // facing this many degrees counterclockwise from the x-axis

    // start at (x0, y0), facing a0 degrees counterclockwise from the x-axis
    public Turtle(double x0, double y0, double a0) {
        x = x0;
        y = y0;
        angle = a0;
    }

    // rotate orientation delta degrees counterclockwise
    public void turnLeft(double delta) {
        angle += delta;
    }

    // move forward the given amount, with the pen down
    public void goForward(double step) {
        double oldx = x;
        double oldy = y;
        x += step * Math.cos(Math.toRadians(angle));
        y += step * Math.sin(Math.toRadians(angle));
        StdDraw.line(oldx, oldy, x, y);
    }

    // pause t milliseconds
    public void pause(int t) {
        StdDraw.show(t);
    }


    public void setPenColor(Color color) {
        StdDraw.setPenColor(color);
    }

    public void setPenRadius(double radius) {
        StdDraw.setPenRadius(radius);
    }

    public void setCanvasSize(int width, int height) {
        StdDraw.setCanvasSize(width, height);
    }

    public void setXscale(double min, double max) {
        StdDraw.setXscale(min, max);
    }

    public void setYscale(double min, double max) {
        StdDraw.setYscale(min, max);
    }


    // sample client for testing
    public static void main(String[] args) {
        double x0 = 0.5;
        double y0 = 0.0;
        double a0 = 60.0;
        double step = Math.sqrt(3)/2;
        Turtle turtle  = new Turtle(x0, y0, a0);
        turtle.goForward(step);
        turtle.turnLeft(120.0);
        turtle.goForward(step);
        turtle.turnLeft(120.0);
        turtle.goForward(step);
        turtle.turnLeft(120.0);
    }

}

Turtle使用这个类:StdDraw这就是我要粘贴的代码行太多了。

当我执行螺旋时,我一直收到错误:

java.lang.ArrayIndexOutOfBoundsException: 0
    at Spiral.main(Spiral.java:4)

不确定原因。任何人都可以帮助我,所以我可以玩这个吗?

1 个答案:

答案 0 :(得分:2)

您是否指定了两个命令行参数?看起来它需要步数和衰减作为参数,如果你没有指定这些步骤就会崩溃。

例如:

java Spiral 10 1.1