简体   繁体   English

加载文件时程序退出

[英]Program exits when file is loaded

I'm having trouble with a program that unexpectedly closes after a file is loaded. 我在加载文件后意外关闭的程序遇到麻烦。 The program is meant to open a file, announce the errors, and display all the valid numbers. 该程序旨在打开文件,宣布错误,并显示所有有效数字。

Here's the main code: 这是主要代码:

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: 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

The error comes in Project3.handleFile where the errors would be displayed in messages, but the program wouldn't show the numbers on the window. 错误出现在Project3.handleFile中,该错误将在消息中显示,但程序不会在窗口上显示数字。 It would continue to print to the console. 它将继续打印到控制台。 In the console, only "Exception while removing reference." 在控制台中,仅“删除引用时发生异常”。 is displayed without anything else saying what the problem could be. 会显示,而没有其他任何说明问题可能出在哪里。 Nowhere in my code is this shown. 这在我的代码中没有显示。 Why is the program terminating after displaying the errors and not showing the numbers onto the window? 为什么程序在显示错误并且没有在窗口上显示数字后终止?

EDIT: This is the TemperatureGUI 编辑:这是TemperatureGUI

import java.awt.GridLayout;

import javax.swing. 导入javax.swing。 ; ; import java.awt. 导入java.awt。 ; ;

public class TemperatureGUI extends JFrame{ 公共类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);

}//create Menu } //创建菜单

//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

As for the input. 至于输入。 My professor provided us a TextFileInput class which is to be used to retrieve data, line by line, from a text file. 我的教授为我们提供了一个TextFileInput类,该类将用于从文本文件中逐行检索数据。 I've tried things such as the break points, but it doesn't seem to be helping. 我已经尝试过诸如断点之类的事情,但是似乎没有帮助。

There's a semicolon in an unusual place in this bit of the code: 在这段代码的不寻常地方有一个分号:

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

The first semicolon ends the if statement, so System.exit(0); 第一个分号以if语句结尾,因此System.exit(0); on the next line gets called regardless of what happened earlier. 不管之前发生什么,都会在下一行调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM