Javascript 如何使用toString方法将我的坐标转换为上下左右
我希望Javascript 如何使用toString方法将我的坐标转换为上下左右,javascript,java,tostring,Javascript,Java,Tostring,我希望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() s
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>"
newdirection(-1,1).toString()应该给出“”。
新方向(1,-1)。toString()应给出“”
新方向(1,0)。toString()应给出“”
新方向(0,-1)。toString()应给出“”
鉴于您正在重写Direction类的toString()方法,也是为了解决问题,让Direction.x和Direction.y成为Direction类中的一些变量(您从未在问题语句中指定),您可以这样做
@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>";
}
}
@覆盖
公共字符串toString()
{
//测试(-1,1)
if(this.x<0&&this.y>0)
{
返回“”;
}
//测试(1,-1)
else if(this.x>0&&this.y<0)
{
返回“”;
}
//测试(1,0)
else if(this.x>0&&this.y==0)
{
返回“”;
}
//因为上面没有执行任何一个,所以我们假设它是(0,-1)情况
其他的
{
返回“”;
}
}
最后,你的指导课必须看起来像这样才能正常工作
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>";
}
}
}
公共类方向
{
//你是新来的,所以我不会把你和公共的、受保护的和私人的混淆在一起
公共int x;
公共智力;
公共方向(内扎尔格、内扎尔格)
{
这个.x=xArg;
这个.y=yArg;
}
public Direction()//没有参数构造函数,请在此处提供默认值
{
//这真的可以初始化以适合您的口味
这个.x=-1;
这个y=1;
}
@凌驾
公共字符串toString()
{
//测试(-1,1)
if(this.x<0&&this.y>0)
{
返回“”;
}
//测试(1,-1)
else if(this.x>0&&this.y<0)
{
返回“”;
}
//测试(1,0)
else if(this.x>0&&this.y==0)
{
返回“”;
}
//因为上面没有执行任何一个,所以我们假设它是(0,-1)情况
其他的
{
返回“”;
}
}
}
我真的不知道如何让您理解一个非常基本的if-else-if流,但在将此代码放入Direction类之后,并且知道有一些int变量x和y,调用new Direction(-1,1).toString()新方向(1,-1).toString()新方向(1,0).toString()和新方向(0,-1)。toString()将为您提供适当的结果 这似乎是if-else-if检入toString()方法的一个简单例子,您将获得比答案更多的反对票:(哈哈,为什么要投否决票?可能是因为这是一个非常基本的问题,再加上这个问题也与javascripting无关,所以这里的开发人员对这些问题非常敏感。但我保证我不是投否决票的人:Dcan you help我对这一点很陌生,我需要一些帮助。问这么简单的问题,你实际上是在说你不愿意做任何研究。你不准备(或不想)学习。这很可能会阻止其他人帮助你。