【问题标题】:calculating average of values in column of an array?计算数组列中值的平均值?
【发布时间】:2014-01-22 04:21:52
【问题描述】:

好的,所以我最近询问了如何在 java 中访问数组的各个列,我得到了一个完美的答案。然后,我打算计算诸如此列中的最大值和平均值之类的东西。但是,我遇到了一个问题。为了访问每个值,我假设该列也需要被视为一个数组。但是,我访问每一列的方式是将其存储为双精度列。因此,我不知道如何取每一列并计算东西。任何人都可以帮助我吗?很抱歉在这里发布了这么多看起来似乎没什么的东西,但是我们已经有 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;
    }
}

【问题讨论】:

  • 要获得更好的答案,请阅读:sscce.org 这里有很多不相关的代码..
  • 你没有告诉我们你尝试了什么。我觉得您在不了解 Java 基础知识的情况下从一个问题转到下一个问题。
  • 好吧,我使用答案将字符串数组中的数据解析为双精度值,然后保存各个列,但是当我尝试将各个列拆分为一个数组时,它不能;t cuz狭缝方法适用于字符串值。所以我不知道如何取列 c4,它是数组中列中数字的 double 值,然后分别处理其中的每个值进行计算。
  • 如果您将代码滚动到正确的位置,则块模式会产生波动。或者,如果你转过头,建筑物。

标签: java arrays file csv


【解决方案1】:

问题出在这里:

 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. 将所有值存储在数组列表中,并在最后计算平均值。

示例:

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;

【讨论】:

  • 这很有意义。我被困在这段代码上很长时间了,我什至从来没有点击过这些是在循环中创建的。我觉得比我更愚蠢 x) 非常感谢 :)
  • 所以,+= 运算符就像将该列中的每个值添加到变量 c4avg 中,但是我如何将值单独添加到数组或列表中?我试着写成 double[] c4vals += Double.parseDouble(temp[3]);但这不起作用 x)
  • 非常感谢,你是救命稻草 :)
猜你喜欢
  • 2023-03-24
  • 2012-06-03
  • 2013-10-25
  • 1970-01-01
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多