Design a GUI program to find the weighted average of four test scores. The four test scores and their respective weights are given in the following format:
testscore1 weight1
...
For example, the sample data is as follows:
75 0.20
95 0.35
85 0.15
65 0.30
The user is supposed to enter the data and press a Calculate button. The program must display the weighted average.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WeightedAverageJFrame extends JFrame {
private JTextField[] txtScores = new JTextField[4];
private JTextField[] txtWeights = new JTextField[4];
private JButton btnCalculate;
/**
* Constructor
*/
public WeightedAverageJFrame() {
setTitle("Weighted Average");
setSize(300, 200);
setLayout(new BorderLayout());
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//add the main Panel
JPanel pnlControls = new JPanel(new GridLayout(5, 3));
add("Center", pnlControls);
pnlControls.add(new JLabel());
pnlControls.add(new JLabel("Score"));
pnlControls.add(new JLabel("Weight"));
//add Labels and TextFields
for (int i = 0; i < txtScores.length; ++i) {
pnlControls.add(new JLabel("Test score " + (i + 1)));
txtScores[i] = new JTextField();
txtWeights[i] = new JTextField();
pnlControls.add(txtScores[i]);
pnlControls.add(txtWeights[i]);
}
//add the button "Calculate"
btnCalculate = new JButton("Calculate");
btnCalculate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double totalWeightedScore = 0.0;
double totalWeight = 0.0;
try {
for (int i = 0; i < txtScores.length; ++i) {
double score = Double.parseDouble(txtScores[i].getText());
double weight = Double.parseDouble(txtWeights[i].getText());
if (score < 0.0 || weight < 0.0) {
throw new Exception();
}
//calculate total weighted score
totalWeightedScore += score * weight;
//calculate total weight
totalWeight += weight;
}
} catch (Exception var11) {
JOptionPane.showMessageDialog(null, "The input values are not must be positive numbers.");
}
if (totalWeight != 1.0) {
JOptionPane.showMessageDialog(null, "The total weight is not 100%");
} else {
JOptionPane.showMessageDialog(null, "The weighted average is: " + totalWeightedScore);
}
}
});
this.add("South", btnCalculate);
}
/**
* Main method
* @param args
*/
public static void main(String[] args) {
WeightedAverageJFrame weightedAverage = new WeightedAverageJFrame();
weightedAverage.setVisible(true);
}
}
Comments
Leave a comment