Plum average yield calculation task ready

This commit is contained in:
2022-06-02 11:06:40 +03:00
parent 7a3fc9d7d4
commit 0d6dc96bc9
3 changed files with 48 additions and 1 deletions

View File

@@ -149,6 +149,30 @@ public class DataTableModel extends AbstractTableModel {
return targetPos;
}
public double getPlumHarvestAvg() {
double harvest = 0;
int counter = 0;
for (int row = 0; row < getRowCount(); row++) {
for (int col = 0; col < getColumnCount(); col++) {
Data cell = rowData[row][col];
// Check if cell contains plum tree
if (cell.getTree().equals("Слива")) {
harvest += cell.getHarvest();
counter++;
}
}
}
// Avoid division by 0 in case there are no plum trees
if (counter > 0) {
// Find avg
harvest /= counter;
}
return harvest;
}
public String[] getColumnNames() {
return columnNames;
}

View File

@@ -0,0 +1,20 @@
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MenuActionGetPlumHarvestAvg implements ActionListener {
private DataTableModel tableModel;
public MenuActionGetPlumHarvestAvg(DataTableModel tableModel) {
this.tableModel = tableModel;
}
public void actionPerformed(ActionEvent e) {
System.out.println("Find average plum harvest");
double plumHarvestAvg = tableModel.getPlumHarvestAvg();
String text = String.format("Средняя урожайность слив: %.3f", plumHarvestAvg);
JOptionPane.showMessageDialog(null, text);
}
}

View File

@@ -54,7 +54,10 @@ public class MenuBar extends JMenuBar {
highestHarvestItem.addActionListener(new MenuActionFindHighestHarvest(tableModel));
menu.add(highestHarvestItem);
menu.add(createMockMenuItem("Средн Урожай"));
JMenuItem plumHarvestAvgItem = new JMenuItem("Средн Урожай");
plumHarvestAvgItem.addActionListener(new MenuActionGetPlumHarvestAvg(tableModel));
menu.add(plumHarvestAvgItem);
menu.add(createMockMenuItem("Общий урожай"));
menu.add(createMockMenuItem("Lin Spec"));
menu.add(createMockMenuItem("Сектор К деревьев"));