【问题标题】:Java Multidimensional array with excell file and JFileChooser?带有excel文件和JFileChooser的Java多维数组?
【发布时间】:2013-11-01 15:05:03
【问题描述】:

好的,基本上,我的头很痛,我现在被困住了。所以我有一个程序,它有一个打开按钮和一个文本区域。当您使用 hte 打开按钮时,您将打开一个用 Excel 制作的 csv 文件。我的程序应该打开一个文件,将其附加到文本区域,但随后我试图将所有值存储到一个多维数组中,以便我可以使用另一个类来计算诸如最高值和最低值。到目前为止,我刚刚开始尝试做最高的价值,但我没有运气。该文件打开并附加,但最大值出现某种错误。如果有人可以帮助我解决这个问题,我会非常感谢它。

主类

import java.awt.BorderLayout;
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.JButton;
import javax.swing.JTextField;
import java.awt.TextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;


public class task3 extends JFrame {

    public static JPanel contentPane;
    public JTextField txtOpen;
    public JButton btnOpen;
    public static TextArea textArea;
    int rows = 9, columns = 1441; //Columns up and down, rows across. Number of rows and columns in excell file.
    double[][] data = new double[rows][columns]; //Array to hold the rows and columns. 

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    task3 frame = new task3();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public task3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 560, 350);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        btnOpen = new JButton("Open");
        btnOpen.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {


                try{
                    JFileChooser chooser = new JFileChooser(); //File Chooser
                    chooser.setFileFilter(new FileNameExtensionFilter("Excell CSV Files", "csv"));
                    chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); //Filters for csv file

                    //Get the file
                    int returnVal = chooser.showOpenDialog(task3.contentPane); 
                    File file;
                    if(returnVal == JFileChooser.APPROVE_OPTION) {    
                        file = chooser.getSelectedFile();  
                    }
                    else{
                        file = null;
                    }


                    //Read the file into variable
                    BufferedReader in = new BufferedReader(new FileReader(file));
                    String line = in.readLine();

                    while(line != null){
                        task3.textArea.append(line + "\n");
                        line = in.readLine(); //Print out into text area
                    }

                    for(int i = 0; i < rows; i++){
                        //Use a temporary array to hold the rows in whilst the data is split.
                        String array [] = line.split(","); //Split the data up using the commas.
                        for(int j = 0; j < columns; j++){
                            //Take the rows and columns and convert them into a double so they can be saved into the array.
                            data[i][j] = Double.parseDouble(array[j]);
                        }
                    }

                }catch(Exception e){
                    e.printStackTrace();
                }

                double max = task3Methods.Max(data);
                textArea.append("\n\nmax is: "+max);
            }
        });
        btnOpen.setBounds(256, 22, 89, 23);
        contentPane.add(btnOpen);

        txtOpen = new JTextField();
        txtOpen.setBounds(61, 23, 174, 20);
        contentPane.add(txtOpen);
        txtOpen.setColumns(10);

        textArea = new TextArea();
        textArea.setBounds(27, 57, 507, 245);
        contentPane.add(textArea);
    }
}

方法类

public class task3Methods {

    public static double Max(double[][] data){

        double temp;

        double high = Double.MIN_VALUE;  //State this variable hold the largest possible double in the file.

        for (int i = 0; i < data.length; i++){ //Loop through the data.
            for(int j = 0; j < data[i].length; j++){
                temp = data[i][j];
                if(temp > high){ //If a number in the array is larger than the current highest value...
                    high = temp; //Store the new highest value.
                }               
            }
        }

        return high;
    }
}

这是我在下拉框中使用的 Excel 文件的链接 https://www.dropbox.com/s/62ssjoph2z6vmv3/Temperature_Log.csv

抱歉,这是确切的错误

java.lang.NullPointerException
    at task3$2.mouseClicked(task3.java:86)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

并且在文本区域,而不是说like Max = 21.5456 或其他,它说最大值是:4.9E-324

【问题讨论】:

  • "...but the max value is getting some kind of error." -- 当在这里询问错误时,您总是想向我们展示错误消息本身。仔细阅读此消息通常会向我们(和您)展示问题的原因,并有助于找到解决方案。请为我们发布此内容。
  • 对不起我的错误,我是一个成熟的菜鸟,我已经添加了错误:)
  • 没问题,但我是对的,错误信息是关键。请看这一行,java.lang.NullPointerException at task3$2.mouseClicked(task3.java:86)。您需要告诉我们哪一行是 task3.java 的第 86 行。您尝试在该行上使用的变量为 null。
  • 另外,您永远不想在 JButton 上使用 MouseListener。而是使用 ActionListener,因为它们与按钮配合得更好。
  • 我看到的一个问题是,如果用户拒绝了 JFileChooser 并且 File 变量设置为 null,您仍然尝试读取它。您应该在 if 块的 inside 中打包文件读取代码。

标签: java file multidimensional-array


【解决方案1】:

此部分出现问题:

while (line != null) {
   A.textArea.append(line + "\n");
   line = in.readLine(); // Print out into text area
}

for (int i = 0; i < rows; i++) {
   // Use a temporary array to hold the rows in whilst the data is split.
   String array[] = line.split(","); // Split the data up using the commas.
   for (int j = 0; j < columns; j++) {
      // Take the rows and columns and convert them into a double so they can be saved into the array.
      data[i][j] = Double.parseDouble(array[j]);
    }
}

在您的 while 循环的最后一次迭代之后,in.readLine() 将始终返回 null。您稍后再调用line.split(","),这会导致NullPointerException。如果我理解您的代码,您不想在这里使用line.split(),因为您将所有文件文本附加到A.textArea。相反,您应该做以下两件事之一,或者在从文件中读取文本时将文本存储在数组中,或者使用 A.textArea.getText() 访问之前读取的行。

【讨论】:

  • 对不起,我还在学习atm。因此,通过在已经使用它之后尝试拆分字符串行,它是空的。相反,我应该说 String newArray[] = textarea.getText().split ?
  • textarea.getText.split(",") 将返回一个字符串数组,其中每个条目都是逗号前面的文本。如果这就是您的目标,那应该可行。
  • 好的,修复了空指针错误,但它仍然无法正常工作,现在我在 data[i][j] = Double.parseDouble(array[j]) ;说 java.lang.NumberFormatException: For input string: "Timestamp"
  • 这很自我描述。您正在调用parseDouble,它试图沿“30.20”的行获取一个字符串并将其转换为双精度数。发生异常是因为“时间戳”无法解析为 Double。我不知道您正在阅读的文件的格式,但看起来您正在阅读标题行? p.s.我不能低估调试器在此类问题中的重要性。
  • 这是一个excel文件。在第一个框中显示时间戳,第二个框有一个传感器名称,如 4EZ57,然后是一堆读数,如 19746 21945 16473
猜你喜欢
  • 2013-05-27
  • 1970-01-01
  • 2015-10-08
  • 1970-01-01
  • 2017-08-30
  • 2014-08-14
  • 2016-08-19
  • 2012-12-26
  • 1970-01-01
相关资源
最近更新 更多