计算数组列中值的平均值?

时间:2014-01-04 13:24:56

标签: java arrays file csv

好的,所以我最近问过如何在java中访问数组的各个列,我得到了一个完美的答案。然后,我打算计算诸如此列中的最大值和平均值之类的内容。但是,我遇到了一个问题。为了访问每个值,我假设此列也需要被视为一个数组。但是,我访问每个列的方式是将其存储为double。因此,我不知道如何采取每列和计算的东西。有人可以帮我吗?我很抱歉发布这么多内容可能在这里似乎没什么,但是我们没有老师已经12周了,并且只是通过教自己来完成这项工作,我真的被困了。

import java.awt.EventQueue;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;//Importing any required tools.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class CSVFiles extends JFrame { //Class, inherits properties of the JFrame. 

    private JPanel contentPane; //Create a container for the GUI.
    //Create other components used in the GUI
    private JTextField maxTxtVCC;
    private JTextField maxTxtTemp;
    private JTextField maxTxtLight;
    private JTextField minTxtLight;
    private JTextField avTxtLight;
    private JTextField minTxtTemp;
    private JTextField avTxtTemp;
    private JTextField minTxtVCC;
    private JTextField avTxtVCC;
    private JButton btnMax;
    private JButton btnMin;
    private JButton btnAv;
    private JTextField opnTxt;
    private JButton btnOpn;
    private TextArea textArea;
    private JFileChooser fc; 

    private String content = "";
    String [] contentCSV = new String [53000]; //String array to hold the data, 2000 gives more than enough space
    int totalValues; //Used to hold the amount of values in the array (52790 ish)
    Double[][] values;
    double c4, c5, c6;


    /**
     * Launch the application.
     */
    public static void main(String[] args) { //Main method
        EventQueue.invokeLater(new Runnable() {
            public void run() { //Create a runnable method
                try {
                    CSVFiles frame = new CSVFiles(); //Launch the GUI
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace(); //Print errors
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public CSVFiles() { //Open constructor

        super ("CSV Files"); //Create a title for the GUI

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Instruct how the GUI is closed
        setBounds(100, 100, 800, 600); //Set size and location
        contentPane = new JPanel(); //Declare the JPanel
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); //Create a boarder
        setContentPane(contentPane); //Add the JPanel
        contentPane.setLayout(null); //Set the layout

        maxTxtVCC = new JTextField(); //Declare this text field
        maxTxtVCC.setBounds(113, 534, 86, 20); //Set size and location
        maxTxtVCC.setEditable(false); //Set it so it cannot be edited
        contentPane.add(maxTxtVCC); //Add to the content pane

        maxTxtTemp = new JTextField(); //Declare this text field
        maxTxtTemp.setBounds(113, 503, 86, 20); //Set size and location
        maxTxtTemp.setEditable(false); //Set it so it cannot be edited
        contentPane.add(maxTxtTemp); //Add to the content pane

        maxTxtLight = new JTextField(); //Declare this text field
        maxTxtLight.setBounds(113, 472, 86, 20); //Set size and location
        maxTxtLight.setEditable(false); //Set it so it cannot be edited
        contentPane.add(maxTxtLight); //Add to the content pane

        JLabel lblLight = new JLabel("Light"); //Declare this label
        lblLight.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
        lblLight.setBounds(22, 469, 46, 17); //Set size and location
        contentPane.add(lblLight); //Add to the content pane

        JLabel lblTemp = new JLabel("Temperature"); //Declare this label
        lblTemp.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
        lblTemp.setBounds(10, 503, 109, 17); //Set size and location
        contentPane.add(lblTemp);

        JLabel lblVCC = new JLabel("VCC"); //Declare this label
        lblVCC.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
        lblVCC.setBounds(22, 534, 46, 17); //Set size and location
        contentPane.add(lblVCC); //Add to the content pane

        minTxtLight = new JTextField(); //Declare this text field
        minTxtLight.setBounds(221, 472, 86, 20); //Set size and location
        minTxtLight.setEditable(false); //Set it so it cannot be edited
        contentPane.add(minTxtLight); //Add to the content pane

        avTxtLight = new JTextField(); //Declare this text field
        avTxtLight.setBounds(331, 472, 86, 20); //Set size and location
        avTxtLight.setEditable(false); //Set it so it cannot be edited
        contentPane.add(avTxtLight); //Add to the content pane

        minTxtTemp = new JTextField(); //Declare this text field
        minTxtTemp.setBounds(221, 503, 86, 20); //Set size and location
        minTxtTemp.setEditable(false); //Set it so it cannot be edited
        contentPane.add(minTxtTemp); //Add to the content pane

        avTxtTemp = new JTextField(); //Declare this text field
        avTxtTemp.setBounds(331, 503, 86, 20); //Set size and location
        avTxtTemp.setEditable(false); //Set it so it cannot be edited
        contentPane.add(avTxtTemp); //Add to the content pane

        minTxtVCC = new JTextField(); //Declare this text field
        minTxtVCC.setBounds(221, 534, 86, 20); //Set size and location
        minTxtVCC.setEditable(false); //Set it so it cannot be edited
        contentPane.add(minTxtVCC); //Add to the content pane

        avTxtVCC = new JTextField(); //Declare this text field
        avTxtVCC.setBounds(331, 534, 86, 20); //Set size and location
        avTxtVCC.setEditable(false); //Set it so it cannot be edited
        contentPane.add(avTxtVCC); //Add to the content pane

        btnMax = new JButton("Maximum"); //Declare this button
        btnMax.setBounds(110, 438, 89, 23); //Set size and location
        contentPane.add(btnMax); //Add to the content pane

        btnMin = new JButton("Minimum"); //Declare this button
        btnMin.setBounds(221, 438, 89, 23); //Set size and location
        contentPane.add(btnMin); //Add to the content pane

        btnAv = new JButton("Average"); //Declare this button
        btnAv.setBounds(328, 438, 89, 23); //Set size and location
        contentPane.add(btnAv); //Add to the content pane

        textArea = new TextArea(); //Declare this text area
        textArea.setBounds(22, 55, 551, 367); //Set size and location
        textArea.setEditable(false); //Set it so it cannot be edited
        contentPane.add(textArea); //Add to the content pane

        btnOpn = new JButton("Open File"); //Declare this button
        btnOpn.addActionListener(new ActionListener() { //Add an action listener to this button
            public void actionPerformed(ActionEvent arg0) { //Method for action performed
                try{
                    fc = new JFileChooser(); //Declare the file chooser
                    fc.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); //Add a filter for only choosing CSV files
                    fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter()); //Remove option to select any file type

                    int returnVal = fc.showOpenDialog(contentPane); // Open the file chooser
                    File f; //Create a file to hold the data

                    //If the selected file is approved by the file chooser...
                    if(returnVal == JFileChooser.APPROVE_OPTION){
                        f = fc.getSelectedFile(); //Stored selected file into file variable

                        BufferedReader in = new BufferedReader(new FileReader(f));
                        StringBuilder builder = new StringBuilder();
                        String line = "";

                        textArea.append("Opening "+ f.getAbsolutePath()); //Print out file path
                        textArea.append("\nLoading file...\n\n");  //Print out loading message and some new lines

                        in.readLine(); //Skip the first line as it's just headers
                        int index = 0; //Integer used to label the indexes of the array


                            while((line = in.readLine()) != null){
                                builder.append(line);
                                builder.append("\n");
                                index++; //increment the index to move the next one up for the next line

                                String temp[] = line.split(",");
                                c4 = Double.parseDouble(temp[3]);
                                c5 = Double.parseDouble(temp[4]);
                                c6 = Double.parseDouble(temp[5]);
                            }

                        totalValues = index; //Set a value to the total values
                        textArea.append(builder.toString()); //Using the string builder to compile the text
                        textArea.append("\n*** End of File"); //Print the file onto the text area and an end of file message
                        in.close(); //Close the reader.

                        values = new Double [index][3];

                    }
                    else{
                        f = null;
                    }
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        btnOpn.setBounds(484, 26, 89, 23); //Set size and location
        contentPane.add(btnOpn); //Add to the content pane

        opnTxt = new JTextField(); //Declare this text field
        opnTxt.setBounds(22, 27, 452, 20); //Set size and location
        opnTxt.setEditable(false); //Set it so it cannot be edited
        contentPane.add(opnTxt); //Add to the content pane
    }

    //Methods for Calculations
    public static double findMax(double[] array){
        double max;
        max = array[0];

        for(int i=1;i<array.length;++i){
            if(array[i]>max){
                max = array[i];
            }   
        }

        return max;
    }
}

此外,在此之后,我尝试了一个替代代码,而不是获取单独的列,而是将不需要的列存储到数组中,以便它们在计算过程中无效,但这也不起作用。我非常承认我并没有完全理解这种方法,但它是基于给我们的一个示例代码而没有任何解释它正在做什么,所以我想我至少会尝试。它在文本区域显示文件,但在我尝试单击最大按钮时给出空指针异常。 http://gyazo.com/27ef7cf9f4bc0c72ecdc3c1f84e6d0f8再次,任何帮助。我正试着赶紧去,因为去年我的班级来找我帮忙,我在空闲时间观看了一系列关于java基础知识的系列,所以我们的第一年工作没有遇到麻烦,他们来找我帮忙。但是,我没有在这样的东西上找到任何java系列或任何东西,就像特定的视频只能帮助一点点。所以,是的,非常感谢任何帮助。 :)

import java.awt.EventQueue;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;//Importing any required tools.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class CSVFiles extends JFrame { //Class, inherits properties of the JFrame. 

    private JPanel contentPane; //Create a container for the GUI.
    //Create other components used in the GUI
    private JTextField maxTxtVCC;
    private JTextField maxTxtTemp;
    private JTextField maxTxtLight;
    private JTextField minTxtLight;
    private JTextField avTxtLight;
    private JTextField minTxtTemp;
    private JTextField avTxtTemp;
    private JTextField minTxtVCC;
    private JTextField avTxtVCC;
    private JButton btnMax;
    private JButton btnMin;
    private JButton btnAv;
    private JTextField opnTxt;
    private JButton btnOpn;
    private TextArea textArea;
    private JFileChooser fc; 

    private String content = "";
    String [] contentCSV = new String [53000]; //String array to hold the data, 2000 gives more than enough space
    int totalValues; //Used to hold the amount of values in the array (52790 ish)
    Double[][] values;


    /**
     * Launch the application.
     */
    public static void main(String[] args) { //Main method
        EventQueue.invokeLater(new Runnable() {
            public void run() { //Create a runnable method
                try {
                    CSVFiles frame = new CSVFiles(); //Launch the GUI
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace(); //Print errors
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public CSVFiles() { //Open constructor

        super ("CSV Files"); //Create a title for the GUI

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Instruct how the GUI is closed
        setBounds(100, 100, 800, 600); //Set size and location
        contentPane = new JPanel(); //Declare the JPanel
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); //Create a boarder
        setContentPane(contentPane); //Add the JPanel
        contentPane.setLayout(null); //Set the layout

        maxTxtVCC = new JTextField(); //Declare this text field
        maxTxtVCC.setBounds(113, 534, 86, 20); //Set size and location
        maxTxtVCC.setEditable(false); //Set it so it cannot be edited
        contentPane.add(maxTxtVCC); //Add to the content pane

        maxTxtTemp = new JTextField(); //Declare this text field
        maxTxtTemp.setBounds(113, 503, 86, 20); //Set size and location
        maxTxtTemp.setEditable(false); //Set it so it cannot be edited
        contentPane.add(maxTxtTemp); //Add to the content pane

        maxTxtLight = new JTextField(); //Declare this text field
        maxTxtLight.setBounds(113, 472, 86, 20); //Set size and location
        maxTxtLight.setEditable(false); //Set it so it cannot be edited
        contentPane.add(maxTxtLight); //Add to the content pane

        JLabel lblLight = new JLabel("Light"); //Declare this label
        lblLight.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
        lblLight.setBounds(22, 469, 46, 17); //Set size and location
        contentPane.add(lblLight); //Add to the content pane

        JLabel lblTemp = new JLabel("Temperature"); //Declare this label
        lblTemp.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
        lblTemp.setBounds(10, 503, 109, 17); //Set size and location
        contentPane.add(lblTemp);

        JLabel lblVCC = new JLabel("VCC"); //Declare this label
        lblVCC.setFont(new Font("Tahoma", Font.BOLD, 14)); //Set the font and size of text
        lblVCC.setBounds(22, 534, 46, 17); //Set size and location
        contentPane.add(lblVCC); //Add to the content pane

        minTxtLight = new JTextField(); //Declare this text field
        minTxtLight.setBounds(221, 472, 86, 20); //Set size and location
        minTxtLight.setEditable(false); //Set it so it cannot be edited
        contentPane.add(minTxtLight); //Add to the content pane

        avTxtLight = new JTextField(); //Declare this text field
        avTxtLight.setBounds(331, 472, 86, 20); //Set size and location
        avTxtLight.setEditable(false); //Set it so it cannot be edited
        contentPane.add(avTxtLight); //Add to the content pane

        minTxtTemp = new JTextField(); //Declare this text field
        minTxtTemp.setBounds(221, 503, 86, 20); //Set size and location
        minTxtTemp.setEditable(false); //Set it so it cannot be edited
        contentPane.add(minTxtTemp); //Add to the content pane

        avTxtTemp = new JTextField(); //Declare this text field
        avTxtTemp.setBounds(331, 503, 86, 20); //Set size and location
        avTxtTemp.setEditable(false); //Set it so it cannot be edited
        contentPane.add(avTxtTemp); //Add to the content pane

        minTxtVCC = new JTextField(); //Declare this text field
        minTxtVCC.setBounds(221, 534, 86, 20); //Set size and location
        minTxtVCC.setEditable(false); //Set it so it cannot be edited
        contentPane.add(minTxtVCC); //Add to the content pane

        avTxtVCC = new JTextField(); //Declare this text field
        avTxtVCC.setBounds(331, 534, 86, 20); //Set size and location
        avTxtVCC.setEditable(false); //Set it so it cannot be edited
        contentPane.add(avTxtVCC); //Add to the content pane

        btnMax = new JButton("Maximum"); //Declare this button
        btnMax.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                double tempArray1 [] = new double [totalValues];
                double tempArray2 [] = new double [totalValues];
                double tempArray3 [] = new double [totalValues];

                for (int i = 0; i < totalValues; i++){
                    tempArray1[i] = values[i][0]; //assign the indexes along side each individual sensor from sensor value
                    tempArray2[i] = values[i][1];
                    tempArray3[i] = values[i][2];
                }

                //execute the method defined in Utils.java to calculate maximum
                maxTxtLight.setText(findMax(tempArray1)+"");
                maxTxtTemp.setText(findMax(tempArray2)+"");
                maxTxtVCC.setText(findMax(tempArray3)+"");
            }
        });
        btnMax.setBounds(110, 438, 89, 23); //Set size and location
        contentPane.add(btnMax); //Add to the content pane

        btnMin = new JButton("Minimum"); //Declare this button
        btnMin.setBounds(221, 438, 89, 23); //Set size and location
        contentPane.add(btnMin); //Add to the content pane

        btnAv = new JButton("Average"); //Declare this button
        btnAv.setBounds(328, 438, 89, 23); //Set size and location
        contentPane.add(btnAv); //Add to the content pane

        textArea = new TextArea(); //Declare this text area
        textArea.setBounds(22, 55, 551, 367); //Set size and location
        textArea.setEditable(false); //Set it so it cannot be edited
        contentPane.add(textArea); //Add to the content pane

        btnOpn = new JButton("Open File"); //Declare this button
        btnOpn.addActionListener(new ActionListener() { //Add an action listener to this button
            public void actionPerformed(ActionEvent arg0) { //Method for action performed
                try{
                    fc = new JFileChooser(); //Declare the file chooser
                    fc.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); //Add a filter for only choosing CSV files
                    fc.removeChoosableFileFilter(fc.getAcceptAllFileFilter()); //Remove option to select any file type

                    int returnVal = fc.showOpenDialog(contentPane); // Open the file chooser
                    File f; //Create a file to hold the data

                    //If the selected file is approved by the file chooser...
                    if(returnVal == JFileChooser.APPROVE_OPTION){
                        f = fc.getSelectedFile(); //Stored selected file into file variable

                        BufferedReader in = new BufferedReader(new FileReader(f));
                        StringBuilder builder = new StringBuilder();
                        String line = "";

                        textArea.append("Opening "+ f.getAbsolutePath()); //Print out file path
                        textArea.append("\nLoading file...\n\n");  //Print out loading message and some new lines

                        in.readLine(); //Skip the first line as it's just headers
                        int index = 0; //Integer used to label the indexes of the array


                            while((line = in.readLine()) != null){
                                builder.append(line);
                                builder.append("\n");
                                index++; //increment the index to move the next one up for the next line
                            }


                        totalValues = index; //Set a value to the total values
                        textArea.append(builder.toString()); //Using the string builder to compile the text
                        textArea.append("\n*** End of File"); //Print the file onto the text area and an end of file message
                        in.close(); //Close the reader.

                        values = new Double [index][3];

                        for(int i = 0; i < totalValues; i++){
                            String cols[] = contentCSV[i].split(",");

                            String tempMillis = cols[0]; //Use a string to take the millis stamp out of the array
                            String tempStamp = cols[1]; //Use a string to take the time stamp out of the array
                            String tempDateTime = cols[2]; //Use a string to take the date stamp out of the array

                            for(int columns=3;columns<cols.length;++columns){
                                //temp sensor value holds the 9 sensors and the index numbers, parsing the data into double
                                values[i][columns-3] = Double.parseDouble(cols[columns]);
                            }

                        }

                    }
                    else{
                        f = null;
                    }
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        btnOpn.setBounds(484, 26, 89, 23); //Set size and location
        contentPane.add(btnOpn); //Add to the content pane

        opnTxt = new JTextField(); //Declare this text field
        opnTxt.setBounds(22, 27, 452, 20); //Set size and location
        opnTxt.setEditable(false); //Set it so it cannot be edited
        contentPane.add(opnTxt); //Add to the content pane
    }

    //Methods for Calculations
    public static double findMax(double[] array){
        double max;
        max = array[0];

        for(int i=1;i<array.length;++i){
            if(array[i]>max){
                max = array[i];
            }   
        }

        return max;
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于:

 while((line = in.readLine()) != null){
                                builder.append(line);
                                builder.append("\n");
                                index++; //increment the index to move the next one up for the next line

                                String temp[] = line.split(",");
                                c4 = Double.parseDouble(temp[3]);
                                c5 = Double.parseDouble(temp[4]);
                                c6 = Double.parseDouble(temp[5]);
                            }

您将值存储到临时本地(while循环的本地)变量中。 每个循环都会重新分配这些变量,因此您将丢失信息。

你可以做以下两件事之一:

  1. 计算运行的SUM和行数,以便计算最后的平均值。平均值= SUM / COUNT
  2. 将所有值存储在arraylists中,并在最后计算平均值。
  3. 示例:

    double c4avg=0, c5avg=0, c6avg=0;
    
     while((line = in.readLine()) != null){
                                    builder.append(line);
                                    builder.append("\n");
                                    index++; //increment the index to move the next one up for the next line
    
                                    String temp[] = line.split(",");
    //Calculate Running Sum stored in AVG variable
                                        c4avg += Double.parseDouble(temp[3]);
                                        c5avg += Double.parseDouble(temp[4]);
                                        c6avg += Double.parseDouble(temp[5]);
                                    }
    //Divide by total rows to get average
        c4avg/=index;
        c5avg/=index;
        c6avg/=index;