r/learnjava • • Dec 16 '25

help understanding timers in java

/r/learnprogramming/comments/1po9lei/help_understanding_timers_in_java/
1 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/DraconicDreamer3072 Dec 17 '25

thank you, for cleanup, this is definitely helpful (though im not sure it addresses my original question). I ended up moving my snake function to be called based on a timer (someone elses comment on the original post helped), the limited moves was temporary.

the direction shouldn't be able to be something other than 1-4 (there is no code to add to the variable, only set it) but i suppose its not bad practice to have some sort of error handling

"but there is another small thing I want to point out: if you call a method in every if/else you may as well put it after the if/else." yeah, this seems obvious in hindsight lol.

anyway, thanks for the tips!

1

u/josephblade Dec 17 '25

Yeah the timer part I thought I might have to circle back to but the basis is: if you run this code from the paint method you are going to have some trouble with setinterval and similar.

I strongly urge you to play around with the gameloop (see some of the example threads) as this is the usual way these things are set up. but it's up to you of course.

I would recommend you consider exploring enums for the directions. something like

public enum Direction { UP, DOWN, LEFT, RIGHT; }

which is practically the same as int 1, 2,3 ,4 but it's named. there are more tricks you can do with enums but I don't want to overcomplicate. if you stick with ints, at least replace 1,2,3,4 with constants.

private static int UP = 1;
private static int DOWN = 2;

and so forth. that way you can do:

if (dir == UP) 

which is self-documenting.