1. Member
Join Date
Jun 2011
Posts
54
Rep Power
0

## "-" problem

Hi! Created class Bug which moving either to the left or right on horizontal line. Initially bug moves right but it can turn to change diretion. in each move its position changes by one unit in the current direction. So we have:

public class Bug {
public Bug(int initialPosition)
{
position=initialPosition;
}
public void turn()
{
position=-position*(-1);
}
public void move()
{
position=position+1;
}
public int getPosition()
{
return position;

}
private int position;
}

and tester:

public class BugTester {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Bug bugsy = new Bug(10);
bugsy.move(); // now the position is 11
bugsy.turn();
bugsy.move(); // now the position is 10
System.out.println(bugsy.getPosition());
}

}
of course it gives us incorrect answer: -10 instead of 10. The problem is I cant construct right algorithm(maybe i am weak in math) that gives me right sign every time when I turn the bug. hope you know smth guys and thanks in advance.

2. Senior Member
Join Date
Oct 2010
Location
Germany
Posts
787
Rep Power
8

## Re: "-" problem

?!?!
a) bugsy.move(); // now the position is 10 - thats wrong! 10+1 = 11 , -11*-1 = 11 + 1 = 12
b) of course it gives us incorrect answer: -10 instead of 10. ?????
c) there is another thread with the exactly same question : Creating a 'turn' method
d) as JoshAs said, notice a direction (int direction = 1) and in your turn method multiply with -1. At your move method simple add the direction to your position (So then you automaticcaly add either +1 or -1)

3. ## Re: "-" problem

Originally Posted by eRaaaa
c) there is another thread with the exactly same question : Creating a 'turn' method
Agreed. Closing this.

FOX427, don't double post and do remember to use code tags for posting code.

db