#Infinite Particle Movement Loop

4 messages · Page 1 of 1 (latest)

past fog
#

The idea behind this code is to have a particle centered at the origin of a square, and to see how many movements it would take the particle to touch the boarder of the square with twice the length of some integer n. Anytime I run it, however, the code refuses to run as if it is trapped in an infinite loop. I even tried implementing a limit the value of variable g in order to stop the loop and the same problem happens. If anyone could spot the error within my code, that would be greatly appreciated.

    public static void main(String[] args) {

        int n = Integer.parseInt(args[0]);
        double n0 = 0;
        double e = 0;
        double s = 0;
        double w = 0;
        int a = 0;
        int b = 0;
        int c = 0;
        int d = 0;
        int g = 0;

        for (double i = Math.random();
             ((g != 5) || (n0 != 2 * n) || (e != 2 * n) || (s != 2 * n) || (w != 2 * n)); ) {
            if (i < 0.25) {
                n0 = n0 + n;
                s = s - n;
                a = a + 1;
                g = g + 1;
            }
            else if (i < 0.5) {
                e = e + n;
                w = w - n;
                b = b + 1;
                g = g + 1;
            }
            else if (i < 0.75) {
                s = s + n;
                n0 = n0 - n;
                c = c + 1;
                g = g + 1;
            }
            else {
                w = w + n;
                e = e - n;
                d = d + 1;
                g = g + 1;
            }
        }
        System.out.println("The particle moved north " + a + " times.");
        System.out.println("The particle moved east " + b + " times.");
        System.out.println("The particle moved south " + c + " times.");
        System.out.println("The particle moved west " + d + " times.");
        System.out.println("The particle moved " + g + " times.");
    }
}
molten nymphBOT
#

This post has been reserved for your question.

Hey @past fog! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

molten nymphBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping.
Warning: abusing this will result in moderative actions taken against you.