既然你要重寫你的方向類的toString()方法,也爲你的問題的緣故,讓Direction.x和Direction.y是你的方向類中的一些變量(你的問題陳述從未指定),你可以去這樣
@Override
public String toString()
{
// Testing for (-1 , 1)
if(this.x < 0 && this.y > 0)
{
return "<up right>";
}
// Testing for (1 , -1)
else if(this.x > 0 && this.y < 0)
{
return "<down left>";
}
// Testing for (1 , 0)
else if(this.x > 0 && this.y == 0)
{
return "<down>";
}
// Since none of the above executed, we assume that it's (0 , -1) case
else
{
return "<up>";
}
}
所以最後真的是你的方向類必須是這個樣子才能正常工作
public class Direction
{
// You are pretty new so I wouldn't confuse you with public,protected and private here
public int x;
public int y;
public Direction(int xArg , int yArg)
{
this.x = xArg;
this.y = yArg;
}
public Direction() // No-Arg Constructor, give default values here
{
// this could really be initialized to fit your taste
this.x = -1;
this.y = 1;
}
@Override
public String toString()
{
// Testing for (-1 , 1)
if(this.x < 0 && this.y > 0)
{
return "<up right>";
}
// Testing for (1 , -1)
else if(this.x > 0 && this.y < 0)
{
return "<down left>";
}
// Testing for (1 , 0)
else if(this.x > 0 && this.y == 0)
{
return "<down>";
}
// Since none of the above executed, we assume that it's (0 , -1) case
else
{
return "<up>";
}
}
}
我真的不能告訴你如何讓你理解一個非常基本的if-else-if流,但是在將這些代碼放在Direction類中並知道有一些int變量x和y後,調用new Direction(-1 ,1).toString();new Direction(1,-1).toString();new Direction(1,0).toString();和新的方向(0,-1).toString()會給你適當的結果;
這似乎是一個簡單的if-else-if檢查toString()方法的情況,並且您將獲得更多的低於答案:( – ShayHaned
lol爲什麼downvotes? – Jkae11
可能是因爲它本質上是非常基本的,加上這個問題也跟javascripting無關,所以這裏的開發人員對這些問題都非常敏感,但我保證我不是那個沮喪的人:D – ShayHaned