I am trying to calculate the miles per gallon per trip & also average miles per gallon overall. The per trip works fine but I can't get the average to work. It is just reading the per trip instead of averaging. Any suggestions? THANKS!

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MPG extends Applet implements ActionListener
{
Label First; //First line
Label Second; //second line
Label Miles;
Label Gallons;
TextField EMiles; //input miles
TextField EGallons; //enter gallons
Label Outp;
Label OutpAgain;

Panel pan1, pan2, pan3, pan4, pan5, pan6;
//setup the graphical user interface components
//and initialize variables
public void init()
{
setLayout(new GridLayout(6,1));
pan1=new Panel();
pan2=new Panel();
pan3=new Panel();
pan4=new Panel();
pan5=new Panel();
pan6=new Panel();
First = new Label ("Here is the output of my program:");
Second = new Label ("Enter information and press enter");
Miles = new Label ("Enter Miles");
Gallons = new Label ("Enter Gallons");
EMiles = new TextField (10);
EGallons = new TextField(10);
Outp = new Label("MPG This tank is ");
OutpAgain = new Label ("TOTAL MPG is ");
EMiles.addActionListener(this);
EGallons.addActionListener(this);

pan1.add(First);
pan2.add(Second);
pan3.add(Miles);
pan3.add(EMiles);
pan4.add(Gallons);
pan4.add(EGallons);
pan5.add(Outp);
pan6.add(OutpAgain);
add(pan1);
add(pan2);
add(pan3);
add(pan4);
add(pan5);
add(pan6);
}
public void actionPerformed (ActionEvent e)
{
float Miles = 0;
float Gallons = 0;
float MPG = 0;
float AMiles = 0;
float AGallons = 0;
float AMPG = 0;


{
Miles = Integer.parseInt(EMiles.getText());
Gallons = Integer.parseInt (EGallons.getText());
EMiles.setText( "" );
EGallons.setText( "");

MPG = Miles/Gallons;
Outp.setText("MPG This Tank is " + MPG);

AMiles = Miles + AMiles;
AGallons = Gallons + AGallons;
AMPG = AMiles/AGallons;
OutpAgain.setText("TOTAL MPH is " + AMPG);
}
}
}

So what's the exact problem? Is you're frame showing up? Is it registering the click? Is something printed on the button?

PS: I'm sure it's gallons/miles.

Actually, if it is suppossed to be a fuel efficiency calculation, then it is miles/gallons (mpg miles per gallon).

The program works fine. I just thought it didn't because I am bad at math -- my mistake.

This article has been dead for over six months. Start a new discussion instead.