Ok I have done this program where there are 2 buttons, one to enter price and one to calc average, so the user enters an randome amount and click the enter price button then user can keep entering more and then click calc average button to get average, but problem is that for some reason the program only works if the user enters 4 amounts. If the user enters 3 orsomething else it doesnt display anything...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Average extends JApplet implements ActionListener
{
Container con = getContentPane();
JLabel displayAverage = new JLabel(); // displays the calculated average price of the numbers entered
JButton enterPrice = new JButton("Enter Price"); // enters the prices entered by the user into memory
JButton calculateAverage = new JButton("Average"); // calculates the average of the prices entered
JTextField userPrice = new JTextField(10); // allows user to enter prices
String[] pricesArray = new String[5];
int count = 0;
public void init()
{
con.add(calculateAverage);
con.add(enterPrice);
con.add(userPrice);
con.add(displayAverage);
con.setLayout(new FlowLayout(FlowLayout.CENTER));
userPrice.requestFocus();
enterPrice.addActionListener(this);
calculateAverage.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source == enterPrice && count<5)
{
pricesArray[count] = userPrice.getText();
userPrice.setText("");
count++;
}
if(source == calculateAverage)
{
double sum = 0;
double average;
for(int i=0; i<pricesArray.length-1;i++)
{
double value = Double.valueOf(pricesArray[i]).doubleValue();
sum = value + sum;
}
average=sum/count;
String str = Double.toString(average);
displayAverage.setText("The Average Price Is: $" + str);
count=0;
}
}
}