0

My program won't print the average I calculated in the action performed method to the GUI.I cant get it to return the average. I have tried everything I can think of. also, I am fairly new at java. please be detailed. thanks!

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

public class blooddriveaverage extends Applet implements ActionListener 
{
 public void init() 
 {
   Label title = new Label("Blood Drive!");
  setBackground(Color.red);
  Label label1 = new Label("Department 1 amount: ");

  textField1 = new TextField(" ");

  avg = new Button("Average");
  clear = new Button ("Clear Fields");
  avg.addActionListener(this);
  clear.addActionListener(this);

  Label label2 = new Label("Department 2 amount: ");
  textField2 = new TextField(" ");
  Label label3 = new Label("Department 3 amount: ");
  textField3 = new TextField(" ");
  Label label4 = new Label("Department 4 amount: ");
  textField4 = new TextField(" ");

  add(title);
  add(label1);
  add(textField1);
  add(label2);
  add(textField2);
  add(label3);
  add(textField3);
  add(label4);
  add(textField4);
  add(avg);
  add(clear);
  add(avgField);
  avg.setBackground(Color.white);
  clear.setBackground(Color.orange);

 }
  public void actionPerformed(ActionEvent e) 
  {
    double average = 0;
   setLayout(new FlowLayout()); 
   int[] myarray = new int[4];
   myarray[0] = Integer.parseInt(textField1.getText().trim());
   myarray[1] = Integer.parseInt(textField2.getText().trim());
   myarray[2] = Integer.parseInt(textField3.getText().trim());
   myarray[3] = Integer.parseInt(textField4.getText().trim());
   if (e.getSource() == avg)
   {
     for(int i = 0; i < myarray.length; i++)
     {
       average += myarray[i];
     }
     average /= 4.00;



   }

   else
   {
    textField1.setText("");
    textField2.setText("");
    textField3.setText("");  
    textField4.setText("");
   }
 }

 TextField textField1, textField2, textField3, textField4, avgField;
 Button avg;
 Button clear;

}
  • 1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson Mar 21 '14 at 03:57

1 Answers1

1
  1. You never initialise avgField which causes a NullPointerException in init when you try and add it to the applet
  2. You never assign the result of average to anything...

For example...

avgField.setText(NumberFormat.getNumberInstance().format(average));

You might like to take a look at Code Conventions for the Java Programming Language, Creating a GUI With JFC/Swing and if you really want to go cutting edge, JavaFX

AWT is seriously out of date...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366