【问题标题】:Trouble getting java methods combined in one main method无法将 java 方法组合到一个主要方法中
【发布时间】:2011-06-25 19:22:38
【问题描述】:
class Bug {

// An ant is represented by the coordinates of its location,
// and the direction it is facing.
Integer x;
Integer y;
Dir dir;

enum Dir { E,W,N,S }
}

Bug(Integer x, Integer y, Dir dir) {
    this.x = x;
    this.y = y;
    this.dir = dir;
}}

class BugWorld {


Integer theBreadth, theHeight;
Board board;
Bug bug;

BugWorld(Integer breadth, Integer height) {
    board = new board(breadth, height);
    bug = new Bug(breadth/2, height/2, Ant.Direction.Y);
    theBreadth = breadth;
    theHeight = height;
}

我已经有以下:

Status status(Integer x, Integer y) {
    return board[x][y];
}


void update(Integer x, Integer y) {
    board[x][y].next();
}

下面这部分是我遇到问题的地方:

/* Take the world of the bug to the next step. */
void step() {
    // 1) Get the state at the present bug position.
          //I've done the following (next line) so far.
           Bug status(Integer x, Integer y); ...?

    // 2) Change the 'status' at that position.
             .............?
}

只是将我遇到问题的这些结合起来。

【问题讨论】:

  • 你想达到什么目的,什么没用?
  • @jootschouten 状态由两个枚举 {Visited, NotVisited} 组成。我想要实现的目标在最后一段代码中突出显示。文本“//到目前为止我已经完成了以下(下一行)”正下方的行。不工作。
  • @jootschouten 我想做的是将错误从board 上的一个地方移到另一个地方(从长远来看)。 board 由坐标 (x,y) 组成。 next() 将状态从 NotVisited 更改为 Visited,反之亦然,具体取决于哪个是初始状态。
  • 请问,您为什么始终使用 Integer 而不是 int?
  • 错误状态(整数 x,整数 y);是没有意义的。即使缺少点,状态也不是静态方法,并且您没有捕获返回值。

标签: java methods accessor mutators


【解决方案1】:

很难理解你想要做什么,但我认为这就是你想要的

void step(){

     //get the location of the bug 
     int x = bug.x;
     int y = bug.y;

     //gets the status of the location of the bug
     Status s = status(x,y);

     //move the bug, or do something based on the status of the place

     //update the status of the location the bug was originally on
     update(x,y)
}

【讨论】:

  • 不,我不是要创建一个新的错误对象,我只是想首先在给定的板上错误的当前位置获取status (x, y) 坐标,然后在第二部分中,更改该位置的“状态”。 Bug 构造函数现在在上面突出显示。
  • 我的代码不符合您的要求吗?第一行获取bug所在位置的状态,下一行修改不?
  • 第一个似乎没有,直到我输入以下内容:Status status = board.status(bug.x,bug.y);
  • 你的 status(x,y) 和 update(x,y) 方法是否与 step() 方法在同一个类中?
猜你喜欢
  • 1970-01-01
  • 2015-01-03
  • 2020-06-20
  • 2018-03-21
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
相关资源
最近更新 更多