Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing an odometer in Java

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?

like image 522
Joshua Craven Avatar asked Sep 18 '26 16:09

Joshua Craven


2 Answers

A suggested implementation

There's no point making the model more complex than it has to be just for the sake of recreating the object mechanically. See John3136's answer for corroboration.

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

  • Wrap above model into an Odometer class
  • Build a view that gets refreshed every rotation
like image 111
calebds Avatar answered Sep 21 '26 06:09

calebds


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.

like image 41
John3136 Avatar answered Sep 21 '26 06:09

John3136



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!