Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / February 2005

Tip: Looking for answers? Try searching our database.

Problems with School Project!

Thread view: 
TuRfYMaN - 08 Feb 2005 17:17 GMT
Hi, sorry but this is going to be a long post. I wrote a program that
simulates a 43 mile section of a turnpike.  Each vehicle object created
passes through 3 filters.  A toll filter and 2 speedtraps.

I can't seem to get the Ticket information to print correctly, and I
don't understand why.  I am using a Measurer interface and then a Filter
Class (VehicleFilter) and then a Stratagy class (FineMeausrer). I've tried
everything I can think of, and it still reports discrepencies... The Avg
will usually print higher than the Max? The math looks right to me.  If
anyone can help, I would greatly appreciate it.

  import java.util.Date;
  import javax.swing.Timer;
  import java.awt.event.ActionListener;
  import java.awt.event.ActionEvent;
  import javax.swing.JOptionPane;

   public class Turnpike{
 
     static int runningTime;
     static boolean SimisDone = false;
     static boolean needDelayChange=true;
 
 
     static Measurer toll = new Toll(0.005, 43);;
     static Measurer trapOne = new FineMeasurer(65, 55, .95);
     static Measurer trapTwo = new FineMeasurer(50, 50, .80);
     static VehicleFilter tollData = new VehicleFilter(toll);
     static VehicleFilter trapOneData = new VehicleFilter(trapOne);
     static VehicleFilter trapTwoData = new VehicleFilter(trapTwo);
     
 
      public static void main(String args[]){
        String inputValue = javax.swing.JOptionPane.showInputDialog("How
many seconds should the simulation run?");
        runningTime = Integer.parseInt(inputValue);
        System.out.println("How many seconds should the simulation run?
"+runningTime);
        System.out.println("[-------------------------------BEGIN
SIMULATION--------------------------------]");
     
     
     //begin elapsedTimer CODE   
         class ElapsedListener implements ActionListener
        {
            public ElapsedListener(int runTime)
           {
           
              currentElapTime = runTime;
              initElapTime = runTime;
           
           }
       
            public void actionPerformed(ActionEvent event)
           {
              if (currentElapTime==initElapTime){
              // System.out.println(currentElapTime);
              //start gen timer here
             
               
                 currentElapTime--;
              }
           
              if (currentElapTime>=0){
                // System.out.println(currentElapTime);
              }
           
              if (currentElapTime==0){
                 System.out.println("[-------------------------------END
OF SIMULATION--------------------------------]");
              //stop gen timer here
                 Simdone();
              }
              currentElapTime--;
           }
       
           private int currentElapTime;
           private int initElapTime;
       
        }
         //end elapsedTimer CODE
        
         //begin VehGen Timer Code
     
     
         class VehGenListener implements ActionListener
        {
            public void actionPerformed(ActionEvent event)
           {
           //veh gen code here
              Date time = new Date();
              Vehicle vehicle = TurnpikeVehicleGenerator.newVehicle();
           
           //              int wheels = vehicle.getWheels();
           //                String name= vehicle.toString();
           //                int speed = vehicle.getSpeed();
           //                int instSpeed = vehicle.getInstSpeed();
              
              tollData.add(vehicle);
               trapOneData.add(vehicle);
                    trapTwoData.add(vehicle);
              System.out.println(" "+time.toString()+"  
"+vehicle.toString());
           
             
              
              
              changeDelay();      
              
           //end VehGen code
           
           }
        }
       
        VehGenListener listener2 = new VehGenListener();
        int initGenDelay = TurnpikeVehicleGenerator.nextDelay()*100;
        Timer VehGenTimer = new Timer(initGenDelay, listener2);
     
        VehGenTimer.start();
        int ELAPSED_DELAY = 1000;
        ElapsedListener listener1 = new ElapsedListener(runningTime);
        Timer elapsedTimer = new Timer(ELAPSED_DELAY, listener1);
        elapsedTimer.start();
     
        while (!SimisDone)
        {
           while(!needDelayChange){
           
           
              initGenDelay = TurnpikeVehicleGenerator.nextDelay()*100;
              VehGenTimer.setDelay(initGenDelay);
              needDelayChange = !needDelayChange;
           }}
        VehGenTimer.stop();
        elapsedTimer.stop();
        report();
        System.exit(0);  
     }        
     
      public static void Simdone(){
        SimisDone = !SimisDone;
     }
     
      public static void changeDelay(){
     
        needDelayChange = !needDelayChange;
     
     }
     
      public static void report(){
        System.out.println("[--------------------------BEGIN
REPORT--------------------------]");
        System.out.println("\n"+"Total Number of Cars:
"+tollData.getTotalCarsAdded());
        
     
     
     
     
        System.out.println("[-------------------TOLL
INFO-------------------]"+"\n");      
        System.out.println("Total Amount of Toll: $" +
tollData.getSum());
        System.out.println("       Max Toll Paid: $" +
tollData.getMaxValue());
        System.out.println("       Avg Toll Paid: $" +
tollData.getAverage());
        System.out.println("\n"+"[----------------FINE
INFO-TRAP1-----------------]");
        System.out.println(" Total Number of Tickets:
"+trapOneData.getMeasuments());         
        System.out.println("           Max Fine Paid:
$"+trapOneData.getMaxValue());
        System.out.println("       Avg Ticket Amount:
$"+trapOneData.getAvgData());
        System.out.println("             Max Speeder:
"+trapOneData.getMaximum());
            System.out.println("             All Tickets: $"+trapOneData.getSum());

         System.out.println("\n"+"[----------------FINE
INFO-TRAP2-----------------]");
        System.out.println(" Total Number of Tickets:
"+trapTwoData.getMeasuments());         
        System.out.println("           Max Fine Paid:
$"+trapTwoData.getMaxValue());
        System.out.println("       Avg Ticket Amount:
$"+trapTwoData.getAvgData());
        System.out.println("             Max Speeder:
"+trapTwoData.getMaximum());
            System.out.println("             All Tickets:
$"+trapTwoData.getSum());
        System.out.println("\n"+"[--------------------------END
REPORT--------------------------]");
        JOptionPane.showMessageDialog(null, "                    
Simulation Complete."+"\n"+"Please Check the I/O Console for Report
Printout.");
        
     }
     
     
  }

  import java.util.Random;    
   class FineMeasurer implements Measurer{
     
     int autoSpdLmt;
     int truckSpdLmt;
     double tiFactor;
     Random r = new Random();
     
     
     
      public FineMeasurer(int autoSpdLmt, int truckSpdLmt, double
tiFactor){
        
        this.tiFactor=tiFactor;
        this.autoSpdLmt=autoSpdLmt;
        this.truckSpdLmt=truckSpdLmt;           
     }
 
      public double measure(Object anObject)
     {
        Vehicle aVehicle = (Vehicle)anObject;
        double mph =  aVehicle.getInstSpeed();
        double fine=0;
     
                
        if (r.nextDouble()*100>=(tiFactor*100)){
           if
((aVehicle.id()).equals("Auto")||(aVehicle.id()).equals("Moto")){
              if (mph>=(autoSpdLmt+15)){
                fine =  100+(((mph-autoSpdLmt)/5)*25);}
              if (mph>autoSpdLmt){
                 return fine = 100;}
           }
     
           if ((aVehicle.id()).equals("Truck")){
             if (mph>=truckSpdLmt+15){
                fine =  100+((mph-truckSpdLmt)/5)*25;;}
             if (mph>truckSpdLmt){
                return fine = 100;}
          }
       }
        
         return fine;
     }
  }

   public class VehicleFilter
  {
 
     public double sum;
     private Vehicle maximum;
     public int count;
     private Measurer measurer;
     int numOfnonZero;
     double maxValue;
       
      public VehicleFilter(Measurer aMeasurer)
     {
        sum = 0;
        count = 0;
        maximum = null;
        this.measurer = aMeasurer;
     }
 
      public void add(Vehicle x)
     {
       
        sum = sum + measurer.measure(x);
        if ((count == 0
           || measurer.measure(maximum)< measurer.measure(x)))
        {
         
           maximum = x;
           maxValue = measurer.measure(maximum);
        }
     
           
        if (measurer.measure(x)>.01){
           numOfnonZero++;
        }
        
     
       
        count++;
     }
     
     /**
     Gets the average of the added data.
     @return the average or 0 if no data has been added
  */
      public double getAverage()
     {
        if (count == 0)
           return 0;
        else
           return sum / count;
     }
 
  /**
     Gets the largest of the added data.
     @return the maximum or 0 if no data has been added
  */
      public Object getMaximum()
     {
        return maximum;
     }   
     
     
      public int getTotalCarsAdded()
     {
        return count;
     }
      public int getMeasuments()
     {
        return numOfnonZero;
     }
 
      public double getMaxValue()
     {
        return measurer.measure(maximum);
     }
      public double getSum()
     {
        return sum;
     }
      public double getAvgData()
     {
        if (count == 0||(sum)==0||numOfnonZero==0)
           return 0;
        else
           return (sum / numOfnonZero);
     }
     
 
  }

import java.util.Random;
public class Auto implements Vehicle{

int mph;
double instSpeed;

    public Auto(int speed){
   
    mph=speed;

    }
   
    public int getSpeed(){
    return mph;
    }
   
    public int getWheels(){
   
    return 4;
    }
   
    public int getInstSpeed(){
   
    Random r = new Random();
    double randDbl = r.nextDouble();
    if(randDbl>=.5){
    instSpeed = mph +(randDbl*5);
    return (int) instSpeed;
   
}
   
    instSpeed = mph  - (randDbl*3);
    return (int) instSpeed;

    }
   
    public String toString(){
   
    return "Automobile"+" with "+getWheels()+" wheels.  
AvgSpeed:"+getSpeed();
   
    }
   
        public String id(){
   
    return "Auto";
    }
   
   
}

There are parts of my program I didn't include, like the Vehicle
interface, the other Vehicle Classes (Truck, and Motorcycle), the
VehicleGenerator Class and the Measurer interface, which has one method,
it takes an object and returns a double.

Thank you!

~Tom~
Ryan Stewart - 09 Feb 2005 01:43 GMT
> Hi, sorry but this is going to be a long post. I wrote a program that
> simulates a 43 mile section of a turnpike.  Each vehicle object created
[quoted text clipped - 6 lines]
> will usually print higher than the Max? The math looks right to me.  If
> anyone can help, I would greatly appreciate it.

[...]
Generally speaking, people aren't going to read through that much code. If it
were compileable and you could give some definite "it does this and it should do
that"'s, we might be able to help you pinpoint some things. If you have a math
question, post the equations in question. Ultimately, you're probably just going
to have to do some debugging to trace your problems to something more concrete.
dar7yl - 09 Feb 2005 03:07 GMT
> Hi, sorry but this is going to be a long post. I wrote a program that
> simulates a 43 mile section of a turnpike.  Each vehicle object created
[quoted text clipped - 6 lines]
> will usually print higher than the Max? The math looks right to me.  If
> anyone can help, I would greatly appreciate it.

Judging by your spelling, there are probably a few lexical errors as well as
logic errors in your program.

To again repeat the wisdom of other posters, you have to trim your question
down to the essence of the problem.  Often, you will discover your error
before you post the email.

regards,
   Dar7yl.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.