Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么要打印此代码;0“;_Java - Fatal编程技术网

Java 为什么要打印此代码;0“;

Java 为什么要打印此代码;0“;,java,Java,我的代码遇到了问题。我知道答案是9,但我的代码打印出0,我不知道为什么。我有两门课让它运行。一个方法类和一个Tester类来检查它是否有效。有人能指出我的错误吗 public class Robot { private int[] hall; private int pos; private boolean facingRight; private boolean forwardMoveBlocked() { if (facingRight) { return

我的代码遇到了问题。我知道答案是9,但我的代码打印出0,我不知道为什么。我有两门课让它运行。一个方法类和一个Tester类来检查它是否有效。有人能指出我的错误吗

public class Robot
{
private int[] hall;
private int pos;
private boolean facingRight;

private boolean forwardMoveBlocked()
{
    if (facingRight) 
    {
        return pos == hall.length - 1;
    }
    else
    {
    return pos == 0;
    }
}

private void move()
{
    if (hall[pos] > 0)
    {
        hall[pos]--;
    }

    if (hall[pos] == 0
    {
        if (forwardMoveBlocked())
        {
            facingRight = !facingRight;
        }
        else
        {
            if (facingRight) 
            {
                pos++;
            }
            else
            {
                pos--;
            }
        }
    }
}

public int clearHall()
{
    int count = 0;
    while (!hallIsClear())
    {
        move();
        count++;
    }
    return count;
}

public boolen hallIsClear()
{   
    return true;
}
}
这是我的测试仪类代码

public class Tester
{
    public static void main(String[] args)
    {
        Robot RobotTest = new Robot();
        System.out.println( RobotTest.clearHall() );
    }
}

您的
while
循环调用NOT
hallIsClear()
,它反过来总是返回
true

因此,不会调用
move()
,也不会增加
count

count
的值保持在
0
并按此返回


顺便说一下,您的代码不会编译,因为
hallIsClear()
返回
boolen
,而不是
boolean
,,因为hallIsClear总是返回true

当你打电话的时候

 while (!hallIsClear())
    {
        move();
        count++;
    }
循环永远不会运行,因为hallIsClear总是返回true。 另一方面,如果您将其更改为

while(hallIsClear())


将有一个无限循环。您必须在代码中遵循不同的设计。

此处缺少一个括号:
如果(霍尔[pos]==0
您是否使用调试器逐步完成了它?您是否在调试器中尝试了此操作?它会立即向您显示问题。
move()
从未调用过,请再看看您的逻辑。boolen不存在,请改用boolean。我调用的方法是clearHall()而不是hallIsClear