如何使用 toString 方法将我的坐标转换为上下左右

How to use toString method to convert my coordinates to up down left right

我想要 toString() 到 return [up, down, right,left] 而不是整数。例如,

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>"

鉴于您要重写 Direction class 的 toString() 方法,同样为了您的问题,让 Direction.x 和 Direction.y 成为您 Direction 中的一些变量class(你从未在问题陈述中指定),你可以这样

@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>"; 
   }

}

所以最终你的方向 class 必须看起来像这样才能正常工作

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 流程,但是在将这段代码放在你的方向 class 之后,并且知道有一些 int 变量 x 和 y , 调用 new Direction(-1 , 1).toString(); new Direction(1,-1).toString(); new Direction(1,0).toString();new Direction(0 , -1).toString() 会给你合适的结果;