Question #3487

Write a program using dynamic arrays to record the high temperatures of last seven days and to display all of them with the average of high temperatures. Use three buttons on the screen, one to enter the temperature, second to display the result and third to exit from program

Expert's answer

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class AppFrame extends JFrame {
private ArrayList<Integer> temp;
public AppFrame() {
& super("Temperature");
& initFrame();
& temp = null;
& setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
& setVisible(true);
}
private void initFrame(){
& setLayout(new GridLayout(3, 1));
& JButton enterTemp = new JButton("Enter temperature");
& JButton displayResult = new JButton("Display result");
& JButton exit = new JButton("Exit");
& enterTemp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
temp = new ArrayList<Integer>();
for (int i=0;i<7;i++)
& temp.add(Integer.parseInt(JOptionPane.showInputDialog("Day "+(i+1)+":")));
}
& });
& displayResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sum = 0;
for (int i=0;i<7;i++)
& sum += temp.get(i);
JOptionPane.showMessageDialog(null, "Average temperature: "+((double)sum)/7);
}
& });
& exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
& });
& add(enterTemp);
& add(displayResult);
& add(exit);
& pack();
}
public static void main(String[] args) {
& AppFrame af = new AppFrame();
}
}

LATEST TUTORIALS
APPROVED BY CLIENTS