我正在尝试使用MoveUp方法修改点值。但是,我在main方法中实例化类及其新值时遇到问题。我宣布Point x1 = new Point();
然后x1.moveUp();
,但moveUp();创建一个错误,该方法不适用于参数。
public class Point {
private int xcoord = 6;
private int ycoord;
public static void main(String[] args) {
Point x1 = new Point();
x1.moveUp();
System.out.print(x1);
}
public Point ()
{
xcoord = 0;
ycoord = 0;
}
public Point (int x, int y)
{
x = 9;
y = 8;
}
public int getX ()
{
return xcoord;
}
public int getY ()
{
return ycoord;
}
public void moveUp(int amount)
{
amount = xcoord + 1;
}
public void moveDown(int amount)
{
amount = ycoord - 2;
}
public void moveRight(int amount)
{
amount = xcoord + 1;
}
public void moveLeft(int amount)
{
amount = xcoord - 1;
}
}
答案 0 :(得分:1)
您的move*
方法逻辑错误。
如果您希望传递移动Point
的金额(如参数名称所暗示的那样),则逻辑应该是更新xcoord
或ycoord
,而不是更新本地变量{ {1}}。
例如,为了向上移动,您应该将amount
添加到amount
:
ycoord
然后你可以用以下方法调用方法:
public void moveUp(int amount)
{
ycoord += amount;
}
答案 1 :(得分:0)
从方法声明中可以看出
public void moveUp(int amount)
它需要一个int参数,所以你的代码应该像
x1.moveUp (50); // or some other input from your program
同时修复move*
方法
答案 2 :(得分:0)
根据您的代码,moveUp方法将'amount'作为参数。但你称之为
x1.moveUp();
即。没有争论。这就是你得到错误的原因。
答案 3 :(得分:0)
public void moveUp(int amount)
{
amount = xcoord + 1;
}
根据您的方法实现,您的方法调用必须是
上移(someIntegerValue)
答案 4 :(得分:0)
关于期望moveUp
作为参数的int
方法的建议都是有效的 - 但我也注意到你在这些方法中所做的事情没有意义 - 比如你分配新的值作为参数传入的amount
。我想您要做的是更新xcoord
或ycoord
这样,您的代码应如下所示:
public void moveUp(int amount)
{
xcoord += (amount+ 1);
}
public void moveDown(int amount)
{
ycoord -=(amount +2);
}
public void moveRight(int amount)
{
xcoord += (amount + 1);
}
public void moveLeft(int amount)
{
xcoord - =(amount+1);
}
正如已经建议的那样,您可以从主要方式调用moveUp
方法:
public static void main(String[] args) {
Point x1 = new Point();
int someAmount = 50;
x1.moveUp(someAmount );
System.out.print(x1);
}
我希望这会有所帮助......
答案 5 :(得分:0)
这些方法声明错误!
public void moveUp(int amount)
{
amount = xcoord + 1;
}
public void moveDown(int amount)
{
amount = ycoord - 2;
}
public void moveRight(int amount)
{
amount = xcoord + 1;
}
public void moveLeft(int amount)
{
amount = xcoord - 1;
}
这些方法每个都有一个amount
参数,我想你想让点向上,向下,向左,向右移动一定量。为此,您不应将xcoord - 1
分配给amount
,因为它没有任何实际意义。而且,你似乎弄乱了x和y坐标。
相反,这样做:
public void moveUp(int amount)
{
ycoord += amount;
}
public void moveDown(int amount)
{
ycoord -= amount;
}
public void moveRight(int amount)
{
xcoord += amount;
}
public void moveLeft(int amount)
{
xcoord -= amount;
}
现在这些方法都是正确的,让我们看看如何正确调用方法。
正如我之前所说,moveXXX
方法需要一定数量作为参数。所以,如果你这样称呼它:
x1.moveUp();
它不起作用,因为moveUp
不知道它应该向上移动多少。你需要给它一个值。让我们说10:
x1.moveUp(10);
现在x1.getX()
将返回10!
另外,我建议你覆盖toString
。这样,println()
实际上可以打印出有意义的内容:
@Override
public String toString() {
return "(" + getX() + ", " + getY() + ")"
}
答案 6 :(得分:0)
public void moveUp(int amount) { amount = xcoord + 1; } 记住这个方法是将int值作为参数值。 所以你需要给出一个特定的int值。 喜欢 : x1.moveUp(500);