0

我正在制作计算加法平均值的程序。程序计算正常,但是当我尝试添加异常处理程序时,我失败了。当我输入数字时,它工作正常,但是当我提交空白空间或其他符号时,每次我转动 push OK 或 x 时,我的错误消息都会弹出。我只是想在我出错(提交空格或其他符号)时这样做,我会弹出错误消息,按 OK,然后继续添加新数字而不会出现任何计算错误。

整个程序:

主要的

package average;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Main extends JFrame{
    public static void main (String []args){

        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JFrame frame = new JFrame("Created by Mac4s");
                frame.setLayout(new BorderLayout());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
                frame.setSize(300,220);
                frame.setResizable(true);

                Surface surfObj = new Surface();
                frame.add(surfObj);         
            }
        }); 
    }
}

表面

package average;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;

public class Surface extends JLabel{
    private JTextField numberTxtFld;
    private JLabel topLabel;
    private JLabel sumLabel;
    private JLabel avgLabel;
    private JLabel maxLabel;
    private JLabel minLabel;
    private JLabel amountLabel;
    private JLabel listLabel;
    private JLabel resultLabel;
    private JLabel sumAnswerFld;
    private JLabel avgAnswerFld;
    private JLabel maxAnswerFld;
    private JLabel minAnswerFld;
    private JLabel amountAnswerFld;
    private JLabel fullListLabel;
    private JList fullList;
    final List<String> numbersList = new ArrayList<String>();
    private JButton submitBtn;
    private JButton closeBtn;
    private JPanel panel;

    private DefaultListModel defaultListModel;

    private int arrayIndex = 0;// used for components adding into array

    public Surface(){   
        defaultListModel = new DefaultListModel();

        panel = new JPanel();
        panel.setBackground(Color.WHITE);
        panel.setSize(290, 180);

        panel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;

        topLabel = new JLabel("Enter your number and push submit");
        topLabel.setFont(new Font("Serif", Font.BOLD, 16));

        gbc.gridwidth = 3;
        gbc.gridx = 0; // column 
        gbc.gridy = 0; // row
        panel.add(topLabel, gbc);
        gbc.gridwidth = 1; // setting grid column with to default

        fullListLabel = new JLabel("Full list");
        fullListLabel.setFont(new Font("Serif", Font.BOLD, 16));
        gbc.gridx = 2;
        gbc.gridy = 1;
        panel.add(fullListLabel, gbc);

        resultLabel = new JLabel("Result: ");
        resultLabel.setFont(new Font("Serif", Font.BOLD, 16));
        gbc.gridwidth = 2;
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(resultLabel, gbc);
        gbc.gridwidth = 1; // setting grid column with to default

        avgLabel = new JLabel("Average");
        avgLabel.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 0;
        gbc.gridy = 3;
        panel.add(avgLabel, gbc);

        sumLabel = new JLabel("Total");
        sumLabel.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 0;
        gbc.gridy = 4;
        panel.add(sumLabel, gbc);

        amountLabel = new JLabel("Amount");
        amountLabel.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 0;
        gbc.gridy = 5;
        panel.add(amountLabel, gbc);

        maxLabel = new JLabel("Max");
        maxLabel.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 0;
        gbc.gridy = 6;
        panel.add(maxLabel, gbc);

        minLabel = new JLabel("Min");
        minLabel.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 0;
        gbc.gridy = 7;
        panel.add(minLabel, gbc);

        avgAnswerFld = new JLabel(" 0");
        avgAnswerFld.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 1;
        gbc.gridy = 3;
        panel.add(avgAnswerFld, gbc);

        sumAnswerFld = new JLabel(" 0");
        sumAnswerFld.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 1;
        gbc.gridy = 4;
        panel.add(sumAnswerFld, gbc);

        amountAnswerFld = new JLabel(" 0");
        amountAnswerFld.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 1;
        gbc.gridy = 5;
        panel.add(amountAnswerFld, gbc);

        maxAnswerFld = new JLabel(" 0");
        maxAnswerFld.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 1;
        gbc.gridy = 6;
        panel.add(maxAnswerFld, gbc);

        minAnswerFld = new JLabel(" 0");
        minAnswerFld.setFont(new Font("Serif", Font.BOLD, 12));
        gbc.gridx = 1;
        gbc.gridy = 7;
        panel.add(minAnswerFld, gbc);

        numberTxtFld = new JTextField();
        numberTxtFld.setColumns(10);
        numberTxtFld.setFont(new Font("Serif", Font.PLAIN, 16));
        gbc.ipady = 10;
        gbc.ipadx = 60;
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(numberTxtFld, gbc);

        fullList = new JList(defaultListModel);
        fullList.setVisibleRowCount(6);
        fullList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        gbc.gridheight = 6;
        gbc.gridx = 2;
        gbc.gridy = 2;
        panel.add(new JScrollPane(fullList), gbc);
        gbc.gridheight = 1; // setting grid column with to default

        submitBtn = new JButton("Submit");
        gbc.ipady = 10;
        gbc.ipadx = 10;
        gbc.gridx = 1;
        gbc.gridy = 1;
        submitBtn.addActionListener(
            new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent event) {
                    boolean error = false;
                    do{
                        try{
                            defaultListModel.clear(); // clear screen and then add new list
                            String text = numberTxtFld.getText();
                            numbersList.add(text);
                            for (Object x : numbersList) {
                                defaultListModel.addElement(x);
                            }   
                            numberTxtFld.setText("");

                            int amount = defaultListModel.getSize(); // amount of added numbers
                            double sum = 0;// total sum of added numbers
                            for (Object x : numbersList) {
                                sum = sum + Integer.parseInt((String) x);
                            }
                            double average = sum / amount; // calculate average number
                            int max = -2147483647; // calculate maximal number
                            for (Object x : numbersList) {
                                if (max <= Integer.parseInt((String) x))
                                    max = Integer.parseInt((String) x);
                            }
                            int min = 2147483647; // calculate min number
                            for (Object x : numbersList) {
                                if (min >= Integer.parseInt((String) x))
                                    min = Integer.parseInt((String) x);
                            }
                            sumAnswerFld.setText(Double.toString(sum));// total sum of added numbers

                            amountAnswerFld.setText(Integer.toString(amount));// amount of added numbers

                            avgAnswerFld.setText(String.format("%.3f", average)); // calculate average number

                            maxAnswerFld.setText(Integer.toString(max));// write maximal

                            minAnswerFld.setText(Integer.toString(min)); // write minimal
                            error = true;
                        } catch (Exception e){
                            JOptionPane.showMessageDialog(null, "Wrong input, try again" , "Error", JOptionPane.PLAIN_MESSAGE);
                        }
                    }while(error == false);
                }// action performed end                    
            }// new  action listener end
        );  // submitbtn.action listener end    
        panel.add(submitBtn, gbc);

        add(panel);
    }
}
4

2 回答 2

4

只需删除do-while循环,在摇摆中,您不需要循环,它不像命令行。

删除这个:

do{

....} while(error==true);

您有很多遗漏,但更正了您的代码。

  1. 消除try-catch
  2. 将以下几行添加到您的代码中:

    // clear screen and then add new list
    String text = numberTxtFld.getText();
    boolean isNumber = false;
    try{
        Integer.parseInt(text);
        numbersList.add(text);
        isNumber = true;
    } catch(NumberFormatException ex){
        //JOptionPane.show.......
        numberTxtFld.setText("");
    }
    if(isNumber){
    defaultListModel.clear();
    for (Object x : numbersList) 
    //......... 
    
于 2013-08-06T10:57:32.940 回答
2

这是一个完全避开对话框弹出窗口的解决方案:使用JFormattedTextField而不是JTextField. 这将自动处理输入错误。如果输入了无效值,默认情况下该无效值将替换为最后一个有效值,但可以使用 更改setFocusLostBehavior。您将使用无参数构造函数构造这样的字段,然后调用setValue(new Integer(0)),然后使用它。如果您需要知道字段中的数字,您可以使用(Integer) getValue().

于 2013-08-06T11:01:21.440 回答