首页 > 解决方案 > 在 Java 中使用两个数组进行计算

问题描述

我有这两个数组,我想用它们来显示最高和最低温度以及所有温度组合的平均值。对于整数,它应该显示最低温度,然后是最高温度。因此,对于数组中的每两个整数,另一个数组中的一年。根据所选年份,我将如何使其仅显示两个整数?yearTemp 在 ComboBox 中使用,并且 2 个整数将显示在不可编辑的文本框中。

/* 
 * Program Name: Temperature Average
 * Author: Cody Tapp
 * Date: July 12, 2018
 * Class: CIT 149 Java I
 * Description: This program will use temperature data from the past 65 years and use that info for the user to lookup
 * high and low temperatures for the month of January and the year selected. Displayed will be the average temperature for that month from 
 * all the years combined. 
 */

// Import gui components
import javax.swing.*;
import java.util.*;
import java.util.Comparator;
import javax.swing.ComboBoxModel;
import java.awt.*;
import java.awt.event.*;

public class TapCoGuiTempAverage extends JFrame
{ // Begin class

    public static void main(String[] args)
    { // Begin main 

        new TapCoGuiTempAverage(); // Calls the TapCoGuiTempAverage method and executes. 

    } // End main

      String[] yearTemp = new String[]
{ "1951", "1952", "1953", "1954",
  "1955", "1956", "1957", "1958",
  "1959", "1960", "1961", "1962",
  "1963", "1964", "1965", "1966",
  "1967", "1968", "1969", "1970",
  "1971", "1972", "1973", "1974",
  "1975", "1976", "1977", "1978",
  "1979", "1980", "1981", "1982",
  "1983", "1984", "1985", "1987",
  "1988", "1989", "1990", "1991",
  "1992", "1993", "1994", "1995",
  "1996", "1997", "1998", "1999",
  "2000", "2001", "2002", "2003",
  "2004", "2005", "2006", "2007",
  "2008", "2009", "2010", "2011",
  "2012", "2013", "2014", "2015",
  "2016"};

    int[] highLowTemp = new int[]
{ 7, 68,  9, 77,  20, 65,  -7, 63,
 -3, 66,  8, 62,  -2, 63,   3, 58,
 -5, 69,  8, 70, -12, 58, -12, 71,
-28, 67, -6, 66, -14, 68, -15, 62,
 10, 73,  0, 64, -12, 60, -14, 66,
  7, 67, -8, 71,   0, 62,  13, 69,
  6, 70, -3, 57, -13, 41,  -6, 60,
  0, 60, 15, 56,  -2, 62, -19, 62,
 11, 57, -2, 61, -16, 63,  -7, 62,
 -2, 61, 18, 67,  13, 68,  14, 62,
  4, 58, 12, 67, -32, 54,   3, 69,
  7, 68, -2, 68,   6, 66,   4, 73,
  5, 69,  3, 61,  11, 72,  -8, 57,
  1, 70,  6, 69,  15, 65,   7, 67,
  1, 70,  0, 60,   2, 57,   3, 62,
 15, 64, 14, 68,  -4, 57,   2, 59,
  5, 64};

    // Objects declared that will be used in GUI
    private JButton buttonCalculate;
    private JButton buttonExit;
    private JComboBox<String> comboYearSelector = new JComboBox<>(yearTemp);
    private JTextField textHighTemp;
    private JTextField textLowTemp;
    private JTextField textAverageHighTemp;
    private JTextField textAverageLowTemp; 


    public TapCoGuiTempAverage() // Operate the GUI and processes all calculations based on selection in combobox
    /** REMOVE VOID TYPE TO COMPILE. **/
    { // Begin method

        // Sets window size, location, text, and close operation. 
        this.setSize(800, 400);
        this.setLocation(400, 400);
        this.setTitle("Daily Temperature");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /**** REMOVE COMMENT, ONLY HERE TO COMPILE UNTIL INNER ACTIONLISTENER CLASS IS WRITTEN.****/
        ButtonListener listen = new ButtonListener();

        JPanel tempPanel = new JPanel(); // Creates panel so objects can be added to the window.        
        JLabel labelYear = new JLabel("Select the year");
        tempPanel.add(labelYear);

        tempPanel.setLayout(new GridLayout(15,6,0,5));

        String[] yearSelection = yearTemp; // ComboBox has a string array that will be used to display options in the dropdown menu
        comboYearSelector.addActionListener(listen); // ComboBox is added as an action listener and executes based on its selection.
        tempPanel.add(comboYearSelector); // ComboBox button is added to the panel. 



        JLabel labelHighTemp = new JLabel("High Temp:");
        tempPanel.add(labelHighTemp);
        textHighTemp = new JTextField(5);
        textHighTemp.setEditable(false);
        tempPanel.add(textHighTemp);

        JLabel labelLowTemp = new JLabel("Low Temp:");
        tempPanel.add(labelLowTemp);
        textLowTemp = new JTextField (5);
        textLowTemp = new JTextField(6);
        textLowTemp.setEditable(false);
        tempPanel.add(textLowTemp);

        JLabel labelAverageHighTemp = new JLabel("Average High:");
        tempPanel.add(labelAverageHighTemp);
        textAverageHighTemp = new JTextField(5);
        textAverageHighTemp.setEditable(false);
        tempPanel.add(textAverageHighTemp);

        JLabel labelAverageLowTemp = new JLabel("Average Low:");
        tempPanel.add(labelAverageLowTemp);
        textAverageLowTemp = new JTextField(5);
        textAverageLowTemp.setEditable(false);
        tempPanel.add(textAverageLowTemp);

        buttonCalculate = new JButton("Lookup Temp.");
        buttonCalculate.addActionListener(listen);
        buttonCalculate.setToolTipText("Looks up the temperature for year selected.");
        tempPanel.add(buttonCalculate);

        buttonExit = new JButton ("Exit");
        buttonExit.addActionListener(listen);
        buttonExit.setToolTipText("Closes the program.");
        tempPanel.add(buttonExit);

        this.add(tempPanel);
        this.setVisible(true);

    } // End method

        private class ButtonListener implements ActionListener
        { // Begin inner class
            public void actionPerformed (ActionEvent e) 
            { // Begin method
                if(e.getSource() == buttonCalculate)
                {
                    String selectedItem = ((String)comboYearSelector.getSelectedItem()); 
                    // Get index of year array
                    for( int i = 0; i< yearTemp.length; i++)
                    {
                        if(yearTemp[i].equals(selectedItem))
                        {
                            int year = i;
                            int index = Arrays.binarySearch(yearTemp, year);
                            int lowTemp = highLowTemp[index*2];
                            int highTemp = highLowTemp[index*2+1];



                            String stringLowTemp = (Integer.toString(lowTemp));
                            String stringHighTemp = (Integer.toString(highTemp));


                            String displayLow = (String.format("%.2f", (stringLowTemp)));
                            String displayHigh = (String.format("%.2f", (stringHighTemp)));


                            textLowTemp.setText(displayLow);
                            textHighTemp.setText(displayHigh);

                        } // End inner if
                    } // End For Loop               
                } // End Outer If

                else if (e.getSource().equals(buttonExit))
                {
                    System.exit(0);
                }
            } // End method
        } // End inner class 
}// End class

标签: javaarraysuser-interfacecomboboxtextbox

解决方案


这是构建yearTemp阵列组合框的示例 GUI,并在选择年份时从阵列中检索相应的高温和低温highLowTemp

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

public class YearTempsTest {
    private static final String [] yearTemp = new String [] {
        "1951", "1952", "1953", "1954", "1955", "1956", "1957", "1958",
        "1959", "1960", "1961", "1962", "1963", "1964", "1965", "1966",
        "1967", "1968", "1969", "1970", "1971", "1972", "1973", "1974",
        "1975", "1976", "1977", "1978", "1979", "1980", "1981", "1982",
        "1983", "1984", "1985", "1987", "1988", "1989", "1990", "1991",
        "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999",
        "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007",
        "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015",
        "2016"};

    private static final int [] highLowTemp = new int [] {
        7, 68,  9, 77, 20, 65, -7, 63, -3, 66, 8, 62, -2, 63, 3, 58,
        -5, 69, 8, 70, -12, 58, -12, 71, -28, 67, -6, 66, -14, 68, -15, 62,
        10, 73, 0, 64, -12, 60, -14, 66, 7, 67, -8, 71, 0, 62, 13, 69,
        6, 70, -3, 57, -13, 41, -6, 60, 0, 60, 15, 56, -2, 62, -19, 62,
        11, 57, -2, 61, -16, 63, -7, 62, -2, 61, 18, 67,  13, 68, 14, 62,
        4, 58, 12, 67, -32, 54, 3, 69, 7, 68, -2, 68, 6, 66, 4, 73,
        5, 69,  3, 61, 11, 72, -8, 57, 1, 70, 6, 69, 15, 65, 7, 67,
        1, 70, 0, 60, 2, 57, 3, 62, 15, 64, 14, 68, -4, 57, 2, 59,
        5, 64};

    public static void main (String [] args) {
        new YearTempsTest().buildGui();
    }

    private void buildGui () {
        JFrame dialog = new JFrame("Year & temps");
        JComboBox<String> yearCombo = new JComboBox<>(yearTemp);
        yearCombo.addItemListener(new YearItemListener());
        dialog.add(yearCombo);  
        dialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        dialog.setLocation(300, 200);
        dialog.setSize(300, 100);
        dialog.setVisible(true);
    }

    private class YearItemListener implements ItemListener {
        @Override public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                String year = (String) e.getItem();
                // get index of year array
                int ix = Arrays.binarySearch(yearTemp, year, Comparator.naturalOrder());
                // get the high low temps using year array index
                int lowTemp = highLowTemp [ix*2];
                int highTemp = highLowTemp [ix*2 + 1];
                // work with the two temp values (show in a text field, etc.)
                System.out.println(year + " -> " + lowTemp + " :: " + highTemp);
            }
        }
    }
}

编辑:请注意,假设yearTemp数组的元素已排序(看起来已经如此)。这是binarySearch正常工作所必需的。


推荐阅读