can anyone fix this program?

here is what the assignment calls for

Due to the high cost of gas we want to keep track of Miles per Gallon. Write a JAVA Application or Applet to keep track of Miles Per Gallon. Driver will input miles driven and gallons used for each tankful. The program should calculate the MPG for that tankful and also the average so far. All the average calculations should use floating point. Have the program check for or catch invalid numeric data and also divide by xeroe. Use textfields for the input and labels for the output.

Here is what I have

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Mpg extends Applet implements ActionListener {

Label prompt1, prompt2, prompt3;
TextField input,output;
TextField input2, output2;

double miles;
double gallons;
double mpg;
int counter;
double tmpg;
double avg;

public void init()


prompt1 = new Label("Enter Information and Press Enter"+"
prompt2 = new Label("Enter Miles ");
prompt3 = new Label(" Enter Gallons ");
input = new TextField(5);
input2 = new TextField(5);
output = new TextField(20);
output2 = new TextField(20);


public void actionPerformed(ActionEvent e)

miles = Double.parseDouble(input.getText());
gallons = Double.parseDouble(input2.getText());

mpg = (miles/gallons);
tmpg =(mpg+mpg);
avg = (tmpg/counter);
output.setText( "MPG this tank is " + mpg);
if (counter <= 1)
output2.setText("Total MPG is " + mpg);
output2.setText("Total Mpg is " + avg);

// catch (NumberFormatException ex) {
// outp.setText("invalid input");


should i be using some array or what to compute my average
or just some for loop, or what?


  • No need to use array to store all the entered data.
    Since the variable tmpg is the sum of all calculated mpg

    I have test your code... and just edit few lines of it, then can run properly.

    You can put the main method in your file... so that you no need to open it with browser.

    /* here is the code */
    public static void main(String [] args)
    Applet app = new Mpg();
    Frame ff = new Frame("haha");
    /* ------------ END ------------*/
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion