# "-" problem

• 03-21-2012, 01:04 AM
FOX427
"-" 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.
• 03-21-2012, 08:28 AM
eRaaaa
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 : http://www.java-forums.org/new-java/...rn-method.html
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)
• 03-21-2012, 03:04 PM
DarrylBurke
Re: "-" problem
Quote:

Originally Posted by eRaaaa
c) there is another thread with the exactly same question : http://www.java-forums.org/new-java/...rn-method.html

Agreed. Closing this.

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

db