Results 1 to 3 of 3
Thread: "-" problem
- 03-21-2012, 12:04 AM #1
Member
- Join Date
- Jun 2011
- Posts
- 40
- 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.
- 03-21-2012, 07:28 AM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
Re: "-" problem
?!?!
Your description is incorrect!
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)
- 03-21-2012, 02:04 PM #3
Similar Threads
-
loop "play again" in an 8 ball game , loops but wont let me answer my "out.print"
By IareSmart in forum New To JavaReplies: 1Last Post: 02-01-2012, 08:37 PM -
Got struck with this :- " Exception in thread "main" java.lang.NullPointerException"
By Vermont in forum New To JavaReplies: 5Last Post: 12-21-2011, 06:44 PM -
problem with argument list and precedence "(" and ")"
By helpisontheway in forum Advanced JavaReplies: 6Last Post: 12-24-2009, 07:50 AM -
MoneyOut.println("It took you (whats wrong?>",year,"<WW?) years to repay the loan")
By soc86 in forum New To JavaReplies: 2Last Post: 01-24-2009, 06:56 PM -
the dollar sign "$", prints like any other normal char in java like "a" or "*" ?
By lse123 in forum New To JavaReplies: 1Last Post: 10-20-2008, 07:35 AM


LinkBack URL
About LinkBacks


Bookmarks