2017-03-11 15 views
-2

我希望toString()返回[up, down, right,left]而不是整数。例如,如何使用toString方法将我的坐标转换为向左下方

new Direction(-1,1).toString() should give "<up right>". 
new Direction(1,-1).toString() should give "<down left>" 
new Direction(1,0).toString() should give "<down>" 
new Direction(0,-1).toString() should give "<left>" 
+0

这似乎是一个简单的if-else-if检查toString()方法的情况,并且您将获得更多的低于答案:( – ShayHaned

+0

lol为什么downvotes? – Jkae11

+0

可能是因为它本质上是非常基本的,加上这个问题也跟javascripting无关,所以这里的开发人员对这些问题都非常敏感,但我保证我不是那个沮丧的人:D – ShayHaned

回答

0

既然你要重写你的方向类的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()会给你适当的结果;

相关问题