java - 编写一个带有两个 int 参数的方法。如何使用下面提供的信息声明更多局部 int 变量

标签 java int bluej local-variables

我编写了一个公共(public)实例方法 moveBy(),其第一个参数是表示移动距离的 int,第二个参数是表示移动方向的 char。它不应该返回任何值。

表 1:方向和相应的 x 和 y 增量

         Direction   xInc    yInc (this is not a code)

Right      'R'        1       0

Left       'L'       -1       0

Up         'U'        0      -1

Down       'D'        0       1

I need to begin by declaring local int variables xInc and yInc and use the table above to set these for the appropriate increments depending on the supplied argument for direction.

This is what I have done so far: please if someone can correct me and help me! many thanks

public void moveBy(int distance, char direction)

 {

int xInc = 0;

int yInc = 0;
}

或者我第一次尝试了这个,但它说“需要标识符”。

int xInc = 1,-1, 0, 0
int yInc = 0, 0, -1, 1

最佳答案

首先,错误来自您用来声明变量的语法:

int xInc = 1; // variable xInc can take only one value (1) and it should be an integer.

yInc相同

如果您要使用 Java,最好从 OOP Principles 开始思考。

您想要实现的是存储带有 X 轴、Y 轴和方向的坐标移动。

在类里面开始建模:

public class Move {

    private int xcoordinate;
    private int ycoordinate;
    private String direction // better if it a enum

    public Move(int xInc, int yInc, String direction) {
         this.xcoordinate = xInc;
         this.ycoordinate = yInc;
         this.direction = direction;
    }

    // getter
    public String getDirection() {
         return direction;
    }
}

当您在类中建模 Action 时,您可以使用它来进行 Action !要获取信息,请利用 setter/getter 。

Move firstMove = new Move(2, 1, "R"); // move 2 in x axis and 1 in y axis, in right direction
Move secondMove = new Move(3, -1, "L"); // move 3 in x axis and -1 in y axis, in left direction

你可以知道摆脱moveBy()方法,因为Move类本身嵌入了移动过程。

而是有一个方法makeMove(Move move)并在其中实现移动过程。

关于java - 编写一个带有两个 int 参数的方法。如何使用下面提供的信息声明更多局部 int 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59682982/

相关文章:

java - 如何修复 Java 回文程序中的错误?

android - 如何检查除法的结果是int还是float

go - 如何修复 Golang 中的 %!(EXTRA int=3) 错误?

java - 如何允许一个变量被各种函数使用? java

java - 如何在 main 方法中调用 setter 方法?

bluej - 你如何在 BlueJ 中设置字体?

java - Java 中的局部作用域

java - 尝试为数组中的按钮指定颜色时数组中出现空点错误

java - 咖啡因 Springboot 集成

java - 这个方法返回什么?