随机行走计划

时间:2014-11-29 21:45:03

标签: java random

我要写一个执行以下操作的程序

'我们假设随机游走发生在方形网格上,点(0,0)位于中心。方形的边界将是一个整数,表示方形上当前位置的最大x和y坐标(因此,对于边界值10,x和y坐标都可以在-10到10之间变化,包括10和10) 。每个步骤将是一个单元向上,一个单元向下,一个单元向左,或一个单元向右。 (没有对角线移动。)'

RandomWalk类将具有以下实例数据(所有类型为int): •当前位置的x坐标 •当前位置的y坐标 •步行中的最大步数 •到目前为止在步行中采取的步骤数 •正方形的边界(正整数 - 位置的x和y坐标可以在正负值之间变化)

  1. 首先声明实例数据(如上所述)并添加以下两个构造函数和toString方法。
  2. a)RandomWalk(int max,int edge) - 初始化RandomWalk对象。最大步数和边界由参数给出。 x和y坐标以及所采取的步数应设置为0.

    b)RandomWalk(int max,int edge,int startX,int startY) - 将最大步数,边界和起始位置初始化为参数给出的步数。

    c)String toString() - 返回一个String,其中包含到目前为止所采取的步数和当前位置 - 该字符串应类似于:Steps:12;职位:( - 3,5)

    所以对于第1部分,这就是我提出的     公共课RandomWalk {

    int max;
    int edge;
    int startX;
    int startY;
    
    public RandomWalk (int max, int edge)
    {
        this.max = max;
        this.edge = edge;
    
    }
    
    public void RandomWalk (int max, int edge, int startX, int startY)
    {
        this.max = max;
        this.edge = edge;
        this.startX = startX;
        this.startY = startY;
    }
    
    public String toString()
    {
        return "Max amount of steps.:" + this.max + ",," + "Edge.:" + this.edge +
                ",," + "Starting position on X.:" + this.startX + ",," + "Starting position of Y.:" + this.startY;
    }
    

    但显然这是测试类

    public static void main (String[] args)
    {
    
        int maxSteps; // maximum number of steps in a walk
        int maxCoord; // the maximum x and y coordinate
        int x, y; // starting x and y coordinates for a walk
        Scanner scan = new Scanner(System.in);
        System.out.println ("\nRandom Walk Test Program");
        System.out.println ();
        System.out.print ("Enter the boundary for the square: ");
        maxCoord = scan.nextInt();
        System.out.print ("Enter the maximum number of steps: ");
        maxSteps = scan.nextInt();
        System.out.print ("Enter the starting x and y coordinates with " +
                "a space between: ");
        x = scan.nextInt();
        y = scan.nextInt();     
    }
    }
    

    我不确定测试程序应该存储什么,我只是想澄清我的代码。

    有没有人能想到的例子可以帮助我朝着正确的方向前进?

1 个答案:

答案 0 :(得分:1)

术语实例数据指的是当一个是created时,类的实例可用的值。从record开始,它们有时称为relationinitial values的属性。除了你所拥有的四个之外,不要忘记到目前为止采取的步骤数量。"所有人都应该是私人的;所有人都有明确的FleetPanel

private int max;
private int edge;
private int startX;
private int startY;
private int stepNumber;

你的构造者看起来不错; main()最终需要创建RandomWalk类的瞬间并调用其中一种方法。例如,

RandomWalk walk = new RandomWalk(42, 100);
walk.start();

将为42创建max100edge,为起始坐标创建零。

作为参考,这个{{3}}动画了几个模拟车辆的典型随机游走。 odometer的字段CabPanel大致对应stepNumber

附录:仔细观察,我发现你的第二个构造函数中有一个虚假的void,好像它是一个方法。同时打印调用walk的{​​{1}}是查看事情是否正常的简单方法。例如,

toString()
相关问题