编写一个java程序,实现计算多 种平均值。 输入若干浮点数,计算多种平均值,增加如下要求: 怎样: ①声明实现Averagable求平均值接口的多个类,提供多种求平均值的方法,详见实验题4-22。②使用文本行数组或表格,数值个数可变。③指定数值范围,若超出,处理异常,用红色标记错误数据,并弹出对话框,给出错误信息。④响应事件:按实际元素个数计算,忽略空值及错误数据,解决除数为0的问题。
时间: 2023-06-27 22:01:52 浏览: 96
以下是一个实现上述要求的Java程序,其中包括了求平均值的接口和多个实现该接口的类,使用了文本行数组存储输入的数据,处理了数值范围超出和除数为0的异常情况,并将错误数据标记为红色并弹出对话框提示。
```java
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
interface Averagable {
double calculateAverage(double[] nums);
}
class ArithmeticMean implements Averagable {
@Override
public double calculateAverage(double[] nums) {
double sum = 0;
int count = 0;
for (double num : nums) {
if (!Double.isNaN(num)) {
sum += num;
count++;
}
}
return count > 0 ? sum / count : Double.NaN;
}
}
class GeometricMean implements Averagable {
@Override
public double calculateAverage(double[] nums) {
double product = 1;
int count = 0;
for (double num : nums) {
if (!Double.isNaN(num) && num > 0) {
product *= num;
count++;
}
}
return count > 0 ? Math.pow(product, 1.0 / count) : Double.NaN;
}
}
class HarmonicMean implements Averagable {
@Override
public double calculateAverage(double[] nums) {
double sum = 0;
int count = 0;
for (double num : nums) {
if (!Double.isNaN(num) && num != 0) {
sum += 1.0 / num;
count++;
}
}
return count > 0 ? count / sum : Double.NaN;
}
}
class WeightedMean implements Averagable {
private double[] weights;
public WeightedMean(double[] weights) {
this.weights = weights;
}
@Override
public double calculateAverage(double[] nums) {
double sum = 0;
double weightSum = 0;
for (int i = 0; i < nums.length; i++) {
if (!Double.isNaN(nums[i]) && weights[i] > 0) {
sum += nums[i] * weights[i];
weightSum += weights[i];
}
}
return weightSum > 0 ? sum / weightSum : Double.NaN;
}
}
public class AverageCalculator {
private JFrame frame;
private JTextField textField;
private JLabel arithmeticMeanLabel;
private JLabel geometricMeanLabel;
private JLabel harmonicMeanLabel;
private JLabel weightedMeanLabel;
private List<Double> dataList;
private double[] data;
private double[] weights;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AverageCalculator window = new AverageCalculator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public AverageCalculator() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("输入数据(以逗号分隔):");
lblNewLabel.setBounds(10, 10, 200, 20);
frame.getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setBounds(220, 10, 200, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("计算平均值");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculateAverages();
}
});
btnNewButton.setBounds(10, 40, 150, 30);
frame.getContentPane().add(btnNewButton);
JPanel panel = new JPanel();
panel.setBounds(10, 80, 400, 160);
panel.setLayout(null);
frame.getContentPane().add(panel);
JLabel lblNewLabel_1 = new JLabel("算术平均值:");
lblNewLabel_1.setBounds(10, 10, 100, 20);
panel.add(lblNewLabel_1);
arithmeticMeanLabel = new JLabel("N/A");
arithmeticMeanLabel.setBounds(120, 10, 100, 20);
panel.add(arithmeticMeanLabel);
JLabel lblNewLabel_2 = new JLabel("几何平均值:");
lblNewLabel_2.setBounds(10, 40, 100, 20);
panel.add(lblNewLabel_2);
geometricMeanLabel = new JLabel("N/A");
geometricMeanLabel.setBounds(120, 40, 100, 20);
panel.add(geometricMeanLabel);
JLabel lblNewLabel_3 = new JLabel("调和平均值:");
lblNewLabel_3.setBounds(10, 70, 100, 20);
panel.add(lblNewLabel_3);
harmonicMeanLabel = new JLabel("N/A");
harmonicMeanLabel.setBounds(120, 70, 100, 20);
panel.add(harmonicMeanLabel);
JLabel lblNewLabel_4 = new JLabel("加权平均值(以逗号分隔):");
lblNewLabel_4.setBounds(10, 100, 200, 20);
panel.add(lblNewLabel_4);
weightedMeanLabel = new JLabel("N/A");
weightedMeanLabel.setBounds(120, 130, 100, 20);
panel.add(weightedMeanLabel);
JTextField weightsField = new JTextField();
weightsField.setBounds(220, 100, 150, 20);
panel.add(weightsField);
weightsField.setColumns(10);
JLabel lblNewLabel_5 = new JLabel("权重:");
lblNewLabel_5.setBounds(180, 100, 40, 20);
panel.add(lblNewLabel_5);
dataList = new ArrayList<Double>();
weights = null;
}
private void calculateAverages() {
String input = textField.getText();
String[] inputSplit = input.split(",");
data = new double[inputSplit.length];
for (int i = 0; i < inputSplit.length; i++) {
try {
double num = Double.parseDouble(inputSplit[i]);
if (num >= 0 && num <= 100) {
data[i] = num;
dataList.add(num);
} else {
data[i] = Double.NaN;
dataList.add(Double.NaN);
textField.setForeground(Color.RED);
showErrorDialog("数据范围错误:请输入0~100之间的数值!");
}
} catch (NumberFormatException e) {
data[i] = Double.NaN;
dataList.add(Double.NaN);
textField.setForeground(Color.RED);
showErrorDialog("数据格式错误:请输入浮点数,用逗号分隔!");
}
}
textField.setForeground(Color.BLACK);
if (dataList.isEmpty()) {
return;
}
double[] nums = new double[dataList.size()];
for (int i = 0; i < dataList.size(); i++) {
nums[i] = dataList.get(i);
}
ArithmeticMean arithmeticMean = new ArithmeticMean();
double arithmeticMeanValue = arithmeticMean.calculateAverage(nums);
if (!Double.isNaN(arithmeticMeanValue)) {
DecimalFormat df = new DecimalFormat("#.##");
arithmeticMeanLabel.setText(df.format(arithmeticMeanValue));
}
GeometricMean geometricMean = new GeometricMean();
double geometricMeanValue = geometricMean.calculateAverage(nums);
if (!Double.isNaN(geometricMeanValue)) {
DecimalFormat df = new DecimalFormat("#.##");
geometricMeanLabel.setText(df.format(geometricMeanValue));
}
HarmonicMean harmonicMean = new HarmonicMean();
double harmonicMeanValue = harmonicMean.calculateAverage(nums);
if (!Double.isNaN(harmonicMeanValue)) {
DecimalFormat df = new DecimalFormat("#.##");
harmonicMeanLabel.setText(df.format(harmonicMeanValue));
}
String weightsInput = weightsField.getText();
if (!weightsInput.isEmpty()) {
String[] weightsSplit = weightsInput.split(",");
if (weightsSplit.length != data.length) {
showErrorDialog("权重个数错误:请输入与数据个数相等的权重!");
return;
}
weights = new double[weightsSplit.length];
for (int i = 0; i < weightsSplit.length; i++) {
try {
double weight = Double.parseDouble(weightsSplit[i]);
if (weight >= 0) {
weights[i] = weight;
} else {
weights[i] = Double.NaN;
weightsField.setForeground(Color.RED);
showErrorDialog("权重错误:请输入非负数!");
return;
}
} catch (NumberFormatException e) {
weights[i] = Double.NaN;
weightsField.setForeground(Color.RED);
showErrorDialog("权重格式错误:请输入浮点数,用逗号分隔!");
return;
}
}
weightsField.setForeground(Color.BLACK);
WeightedMean weightedMean = new WeightedMean(weights);
double weightedMeanValue = weightedMean.calculateAverage(nums);
if (!Double.isNaN(weightedMeanValue)) {
DecimalFormat df = new DecimalFormat("#.##");
weightedMeanLabel.setText(df.format(weightedMeanValue));
}
}
}
private void showErrorDialog(String message) {
JDialog dialog = new JDialog(frame, "错误", true);
JLabel label = new JLabel(message, JLabel.CENTER);
dialog.getContentPane().add(label);
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
}
```
阅读全文