Jump to content

Java Timer loop execution?


Booch

Recommended Posts

Before anything. Here's the question I'm tackling. The question itself is relatively easy to do but I kinda feel like pimping it out a bit
453fa19b11d9dff8d19a83af0585171f.png

Wanted to see if I can loop my whole main in my Run class using real-time(seconds) and then saving the result into an array and printing the array after X loops

 

I've never used Java Timer and oracle docs just hurts my eyes sometimes and would be cool to get any suggestions. Want to experiment some crazy shit

  • Like 1
Link to comment
Share on other sites

  • 5 months later...

Just do what the assignment asks for. Storing the data in an array isn't necessary for the results are quite obvious. Just use a new thread to determine what amount of time you'd like execution to occur on.

import java.util.Random;
 
/**
 * Created by Archon
 */
public class VehicleSimulator {
 
    private static final Random RANDOM = new Random();
 
    public static void main(String[] args) {
        VehicleSimulator camry = new VehicleSimulator(1, 100, 20, 1);
        camry.start();
    }
 
    /**
     * Separator
     */
 
    private int passengers, fuelCap, mpg, gear;
 
    private boolean acc, running;
 
    public VehicleSimulator(int passengers, int fuelCap, int mpg, int gear) {
        this.passengers = passengers;
        this.fuelCap = fuelCap;
        this.mpg = mpg;
        this.gear = gear;
        this.running = true;
    }
 
    private void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(running) {
                    accDec();
                    changeGears();
                    debug();
                    try {
                        Thread.sleep(1000L);
                    } catch(InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, this.getClass().getName()).start();
    }
 
    private void accDec() {
        if(gear == 1) {
            /**
             * Cannot decelerate at this point!
             */
            acc = true;
            return;
        }
        acc = RANDOM.nextBoolean();
    }
 
    private void changeGears() {
        int change = acc ? +1 : -1;
        gear += change;
    }
 
    private void debug() {
        System.out.println("Accelerate: " + acc + "     Gear: " + gear);
    }
 
}
Edited by Archon
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...