Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Problems with Math.Random() in a for loop

  1. #1
    Member
    Join Date
    Oct 2011
    Posts
    35
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Problems with Math.Random() in a for loop

    Hello everyone,
    I have a program here that will display between 2 -4 cars "racing" accross the track. I am trying to get the cars to move at random speeds. Some faster, some slower but always different. I have tried a for loop and if it is working it is so neglible I cannot tell the difference. Here is the code I did for the loop:
    public CarImage() {
         int y = (int)(Math.random() * 10) + 10;
         Timer timer1 = new Timer(y, new ActionListener(){
              public void actionPerformed(ActionEvent e) {
                   x += 10;
                   c ++;
                   repaint();
             }
         });
         timer1.start();
    }

    Here is the complete code in case someone needs to see what is going on:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
     
    public class RacingCar extends JFrame {
     
        public RacingCar() {
            int x = (int)(Math.random() * 3) + 2;
            setLayout(new GridLayout(x, 1, 5,5));
            for (int i = 0; i < x; i++){
                    add(new CarImage());
            }
        }
     
        public static void main(String[] args) {
            JFrame frame = new RacingCar();
            frame.setTitle("Racing Car");
            frame.setSize(1200, 350);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
     
        class CarImage extends JPanel {
            protected int x = 0;
            protected int y = 150;
            protected int z = 300;
            protected int c = 0;
     
            public CarImage() {
                Timer timer1 = new Timer(40, new ActionListener(){
                    public void actionPerformed(ActionEvent e) {
                    x += 10;
                    c ++;
                    repaint();
                    }
                });
                timer1.start();
            }
     
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                    // x = 0;
                    y = getHeight();
                    z = getWidth();
                    g.setColor(Color.WHITE);
                    g.fillRect(0, 0, z, y);
                    Polygon polygon = new Polygon();
                    polygon.addPoint(x + 10, y - 21);
                    polygon.addPoint(x + 20, y - 31);
                    polygon.addPoint(x + 30, y - 31);
                    polygon.addPoint(x + 40, y - 21);
     
                    if (x < z - 50) {
                        g.setColor(Color.BLACK);
                        g.fillOval(x + 10, y - 11, 10, 10);
                        g.fillOval(x + 30, y - 11, 10, 10);
                        g.setColor(Color.BLUE);
                        g.fillRect(x, y - 21, 50, 10);
                        g.setColor(Color.GRAY);
                        g.fillPolygon(polygon);
                        g.setColor(Color.RED);
                    }
                    else
                        x = 0;
                        if (c < z - 86)
                            g.drawString("Clint's Car", c, y - 51);
                        else
                            c = 0;
     
            }
     
        }
    }

    Please note that the loop I tried is NOT in the above program.

    If anyone has a suggestion as to how I can get the different speeds I could use some help. A snippet of code would be nice. Yes this is homework. I did try what I thought would work but obviously it did not work.
    Thank you in advance.


  2. #2
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Problems with Math.Random() in a for loop

    As Math.random() only produces a value between 0.0 and 1.0, the highest value you can expect by multiplying by 10 is 10, and can be as low as 0.
    As you're then using that variable to control the timer, a difference of 0-10 MILLISECONDS, yes milliseconds is what javax.Timer uses (1000 = 1 second) is hardly going to make any difference at all to the car speed, especially since the amount each car moves horizontally is defined by a constant.


    Edit: Just noticed the discrepancy in the single code stub up top compared with the code in the complete class. Which is which? Seems my above answer is pointless in that case.
    The way you've designed the cars really isn't the best way of controlling movement etc, but if you insist, you might just consider generating a random number within a range inside the javax.Timer and adding that to the X variable instead of a constant speed.
    Last edited by newbie; September 27th, 2012 at 03:40 PM.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  3. #3
    Member
    Join Date
    Oct 2011
    Posts
    35
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Problems with Math.Random() in a for loop

    Edit: Just noticed the discrepancy in the single code stub up top compared with the code in the complete class. Which is which? Seems my above answer is pointless in that case.
    Yes there is a discrepancy. I noted that right below the full code.
    I will take your suggestion under advisement. Thank you!

  4. #4
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    661
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Problems with Math.Random() in a for loop

    Please note that the loop I tried is NOT in the above program.
    I saw that yes, and of course wondered why not ,but I also didn't expect you to post two irrelevant versions
    Good luck.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  5. #5
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Problems with Math.Random() in a for loop

    I don't see any basically wrong with the concept. It's a matter of tuning the parameters, I'm thinking.

    Why not experiment with random values that are more spread out (i.e. a greater range)? Make it show what it's using.
    Maybe something like
            public CarImage() {
                 int y = (int)(Math.random() * 20) + 1; // 1..20 Smaller is faster
    .
    .
                            x += 1; // Smaller slows everything down
    .
    .
    .                   });
                 timer1.start();
                 System.out.println("y = " + y); // Make it show what it is using for the Timer parameter
            } // End CarImage()

    For purposes of deciding on the best range for the random stuff, you could even temporarily make the timing stuff get picked up from command line arguments so that you could experiment and "fine tune" heuristically without recompiling. (Although with this small program re-compiling isn't much of a hardship.)


    Cheers!

    Z
    Last edited by Zaphod_b; September 27th, 2012 at 06:29 PM.

Similar Threads

  1. Random math problem generator?
    By CamCompetes in forum Member Introductions
    Replies: 1
    Last Post: March 9th, 2012, 01:42 PM
  2. Need help understanding math.random method.
    By slashdash in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 23rd, 2012, 04:50 PM
  3. display the generated Math.random number
    By PsYNus in forum What's Wrong With My Code?
    Replies: 11
    Last Post: November 2nd, 2011, 10:25 AM
  4. Math.Random()
    By xionyus in forum What's Wrong With My Code?
    Replies: 4
    Last Post: October 26th, 2011, 10:22 PM
  5. Creating a new class and dont know how to generate a random number math code
    By beatlebaby70 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: September 15th, 2011, 03:03 PM