How to avoid getting traveller’s diarrhea in Japan?

I’ve travelled to Japan twice and both the times, I caught a stomach bug within the first 3 days of being in Japan.

Although it wasn’t serious, it wasted 3-4 days of my time in Japan.

I was very careful during my 2nd time but no idea how I got it.

Anyone else who is sensitive to this type of illness when traveling to a new country, can you share a few tips/suggestions on how to avoid this?