This site requires JavaScript, please enable it in your browser!
Greenfoot back
rockon411
rockon411 wrote ...

2017/4/2

Scanner Objects

rockon411 rockon411

2017/4/2

#
I am making an object is able to read and follow instructions. My code compiles, but my object doesn't act how it should. Any insight would be appreciated! This is in my actor class.

public void act()
    {
        if (input.hasNext() == true)
        {
            if (new String(input.next()).equals("left"))
            {
                this.left();
            }
            else if (new String(input.next()).equals("right"))
            {
                this.right();
            }
            else if (new String(input.next()).equals("forward"))
            {
                this.forward();
            }
        }
    }
public void forward()
    {
        move(1);
    }
public void left()
    {
        turn(-90);
    }
public void right()
    {
        turn(90);
    }
Nosson1459 Nosson1459

2017/4/2

#
I (as in maybe not other people) need more information. What is "input"? Show the full class code (Ctrl+A). What isn't cooperating? What happens as opposed to what should? The turn method just rotates the actor a certain amount of degrees. If you want it to face left or right, then you should use turnTowards to face the left or right of the frame.
danpost danpost

2017/4/2

#
You are getting different data for each of the three checks (comparing "left" to the first element, "right" to the second element and "forward to the third). You need to get the element and assign it to a String variable and then compare that variable to the three possibilities. Also, it is always best to compare the unknown to the literal -- not the other way around:
public void act()
{
    if (input.hasNext() == true)
    {
        String command = (String)input.next();
        if ("left".equals(command))
        {
            this.left();
        }
        else if ("right".equals(command))
        {
            this.right();
        }
        else if ("forward".equals(command))
        {
            this.forward();
        }
    }
}
rockon411 rockon411

2017/4/2

#
Thank you!
You need to login to post a reply.