I'm toying with the idea of creating an odometer style app in Java.
Basically I know I could use a series of loops to control the rotation, but I was thinking of doing it mathematically.
So if each dial rotates around ten times, from 0 to 9, and there are six dials, that should make for a total of 1000000 total rotations, if my maths are right.
Math.pow(10, 6);
My question is; what would be the most efficient way of keeping track of the last dials rotation, because like a series of real cogs, for every ten turns of the final dial, the last dial would turn once.
And then for every tenth turn of the second from last dial, the third from last would rotate, and then all the others after it would reset back to zero.
Any advice or suggestions?
Rotation model can be as simple as:
int rotations = 0;
/**
* Increment rotations every rotation
*/
void rotate() {
rotations++;
if (rotations >= Math.pow(10, 6)) // consider extracting as constant
rotations = 0; // reset
}
Then to create the view:
/**
* dial can be from 1 .. 6 (where dial 1 moves every rotation)
*/
int getDialPosition(int dial) {
int pow = Math.pow(10, dial);
return Math.floor((rotations % pow) / (pow / 10));
// above gets the digit at position dial
}
Notes
Think back to design and separation of concerns. What you have here is a display of some number between 0 and 9999999. The odometer is just a "view" of that number. I'd make my model (holds a number and has some method to increment the number) and then write a view to display it in whatever GUI style I choose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With