我正在做一个简单的文字冒险项目。但是,当我运行代码时,当我尝试两次输入向右/向左/向前/向后时,它将不起作用。它只是停止。另外,当我向前执行然后向左执行时,程序将进入我的故障保护模式。不仅如此,故障保护也不起作用。我输入左键,故障保护继续。我该如何解决这些问题?
if(direction.equals("right") || direction.equals("Right"))
{
x++;
System.out.println("You walk to the right.");
direction = key.next();
}
if (direction.equals("left") || direction.equals("Left"))
{
x--;
System.out.println("You walk to the left.");
direction = key.next();
}
if (direction.equals("forward") || direction.equals("Forward"))
{
y++;
System.out.println("You walk Forward.");
direction = key.next();
}
if (direction.equals("backwards") || direction.equals("Backwards"))
{
y--;
System.out.println("You walk backwards.");
direction = key.next();
}
do{
System.out.print("Sorry, you can't do that. Try again:");
direction = key.next();
}while(!direction.equals("right") || !direction.equals("Right") || !direction.equals("left") || !direction.equals("Left") || !direction.equals("forward") || !direction.equals("Forward") || !direction.equals("backwards") || !direction.equals("Backwards") || !direction.equals("c"));
Your
do
block always gets executed because theelse
statement is missing. You probably wanted to doIn your case,
else if
is not exactly mandatory in your case, but it is safer and saves useless comparisons.The last
else
is the one that is really missing.