noobcoder24 noobcoder24 - 3 months ago 31
Java Question

4 Digit Java Counter

Hello I am coding something and I need a four digit counter, that when the method is called increases by one each time until I hit 9999. For example, before I call the method, the counter's value will be 0000. After I call the method it will increase to 0001, then 0002, and so on.

I will also like to be able to individually call each digit. I have no idea how this could be done, if someone can help me that'd be great.

What I tried doing:

private int[] count = new int[4];
private int counter;

private void countUp() {
count[counter++];
if (counter > count.length -1) {
counter = 0;
}
}

Answer

Try this simple solution:

private int[] count = new int[4];
private int counter;

private void countUp() {
  counter++;
  count[0] = counter %10;
  count[1] = counter /10 % 10;
  count[2] = counter /100 % 10;
  count[3] = counter /1000 % 10;
}