簡體   English   中英

加載文件時程序退出

[英]Program exits when file is loaded

我在加載文件后意外關閉的程序遇到麻煩。 該程序旨在打開文件,宣布錯誤,並顯示所有有效數字。

這是主要代碼:

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.*;

public class Project3 {

    static TemperatureGUI myGUI;
    static TemperatureList myList = new TemperatureList();
    static Temperature[] myArray = new Temperature[100];
    static int count = 0;

    public static void main(String[] args) {
        myGUI = new TemperatureGUI();
        myGUI.setVisible(true);
    }//main

    public static boolean isValid(String x) {
        Pattern p;
        Matcher m;
        String pattern = "^-?\\d{1,3}(\\.\\d{1,2})?$";

        p = Pattern.compile(pattern);
        m = p.matcher(x);

        return m.matches();
    }//isValid


    public static void addMore(Temperature x) {
        myList.insert(x); // add new temperature to the list
        myArray[count++] = x;

        SelectionSort newSorted = new SelectionSort(myArray, count);

        myGUI.clear();

        for (int i = 0; i < count; i++) {
            myGUI.appendList(myList.getList(i).toString());
            myGUI.appendArray(newSorted.get(i).toString());

        }

    }//AddMore

    public static void handleFile(File file) {
        TextFileInput in = new TextFileInput(file.getAbsolutePath());

        String line = in.readLine();

        while (line != null) {
            //Need to Convert the String to Temperature
            //Before being able to put it into the Array and List
            try {
                if (!isValid(line))
                    throw new IllegalTemperatureException(line);

                float parsedTemp = Float.parseFloat(line);

                Temperature temp = new Temperature(parsedTemp);

                myArray[count++] = temp;
                myList.insert(temp);
            } catch (IllegalTemperatureException e) {
                JOptionPane.showMessageDialog(null, line + " is not a valid temperature.");
            } finally {
                line = in.readLine();
            }

        }//while


        SelectionSort sortedArray = new SelectionSort(myArray, count);


        //Add it to GUI
        for (int i = 0; i < count; i++) {
            myGUI.appendArray(sortedArray.get(i).toString());
            myGUI.appendList(myList.getList(i).toString());
        }


        for (int i = 0; i < count; i++) {

            System.out.println(myList.getList(i));
        }

    }
}//class

FileMenuHandler.java:

import javax.swing.*;

import java.awt.event.*;
import java.io.File;
import java.util.regex.*;


public class FileMenuHandler implements ActionListener {
    JFrame jframe;
    JFileChooser chooser = new JFileChooser();
    Temperature temp; //new input from "Add"

    /**
     *
     * @param jf Which Jframe the the FileMenuHandler should be on
     */
    public FileMenuHandler(JFrame jf) {
        jframe = jf;
    }//constructor

    /**
     * Checks which item was clicked and act according to to that event
     */
    public void actionPerformed(ActionEvent event) {
        String menuName = event.getActionCommand();

        if (menuName.equals("Open")) {
            int val = chooser.showOpenDialog(null);
            if (val == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                Project3.handleFile(file);
            } else {
                JOptionPane.showMessageDialog(null, "Goodbye, forever! Don't forget the cake!");
            }
        } else if (menuName.equals("Add")) {
            while (true) {
                String input = null;
                //Make sure the input value is valid.
                try {
                    input = JOptionPane.showInputDialog(null, "Input a New Temperature.");

                    if (!isValid(input))
                        throw new IllegalTemperatureException(input);

                    temp = new Temperature(Float.parseFloat(input));
                }

                catch (IllegalTemperatureException ite) {
                    JOptionPane.showMessageDialog(null, input + " is an invalid temperature.");
                }

                //If the valid, then pass the temp value to Project 3 and call on the "addMore" method. 
                Project3.addMore(temp); //add more to the GUI

            }//while
        }//Add


        else if (menuName.equals("Quit"));
        System.exit(0);
    }//event---

    //Make sure the value is okay using Regular Expressions
    public static boolean isValid(String x) {
        Pattern p;
        Matcher m;

        String pattern = "^-?\\d{1,3}(\\.\\d{1,2})?$";

        p = Pattern.compile(pattern);
        m = p.matcher(x);

        return m.matches();
    }//isValid
}//Handler

錯誤出現在Project3.handleFile中,該錯誤將在消息中顯示,但程序不會在窗口上顯示數字。 它將繼續打印到控制台。 在控制台中,僅“刪除引用時發生異常”。 會顯示,而沒有其他任何說明問題可能出在哪里。 這在我的代碼中沒有顯示。 為什么程序在顯示錯誤並且沒有在窗口上顯示數字后終止?

編輯:這是TemperatureGUI

import java.awt.GridLayout;

導入javax.swing。 ; 導入java.awt。 ;

公共類TemperatureGUI擴展了JFrame {

JTextArea txtArray = new JTextArea();
JTextArea txtList = new JTextArea();

JMenuBar menuBar;
JMenuItem item;


public TemperatureGUI(){
    //Set Up the Display
    setTitle("Sorted Numbers");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(200, 444);
    setLayout(new GridLayout(1, 2));
    setResizable(false);
    setLocation(200,200);

    createFileMenu();   

    txtArray.setEditable(false);
    txtList.setEditable(false);

    JScrollPane scrollArray = new JScrollPane(txtArray);
    getContentPane().add(scrollArray);

    JScrollPane scrollList = new JScrollPane(txtList);
    getContentPane().add(scrollList);

    //setVisible(true);


    setResizable(false);
}//create GUI   



public void createFileMenu(){
    menuBar  = new JMenuBar();
    JMenu       fileMenu = new JMenu("File");
    FileMenuHandler fmh  = new FileMenuHandler(this);

    item = new JMenuItem("Open");  
    item.addActionListener( fmh );
    fileMenu.add( item );

    fileMenu.addSeparator();          

    item = new JMenuItem("Add");     
    item.addActionListener( fmh );
    fileMenu.add( item );

    setJMenuBar(menuBar);
    menuBar.add(fileMenu);

    fileMenu.addSeparator();

    item = new JMenuItem("Quit");
    item.addActionListener(fmh);
    fileMenu.add(item);

} //創建菜單

//Separate Methods for Adding New Values
public void appendArray(String tempArray){
    txtArray.append(tempArray+"\n");
}

public void appendList(String tempList){
    txtList.append(tempList +"\n");
}



//Clean out the GUI for updated list
public void clear(){
    txtArray.setText(null);
    txtList.setText(null);
}

   }//TemperatureGUI

至於輸入。 我的教授為我們提供了一個TextFileInput類,該類將用於從文本文件中逐行檢索數據。 我已經嘗試過諸如斷點之類的事情,但是似乎沒有幫助。

在這段代碼的不尋常地方有一個分號:

    else if (menuName.equals("Quit"));
    System.exit(0);

第一個分號以if語句結尾,因此System.exit(0); 不管之前發生什么,都會在下一行調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM