2013-08-06 101 views
0

我正在製作計算添加數字的平均值的程序。程序正常計算,但是當我嘗試添加異常處理程序時,我失敗了。當我把數字,它的工作很好,但是當我提交空白空間或其他標誌,我的錯誤消息保持彈出每次我按下OK或X。我只是想在犯錯誤時提交(提交空格或其他符號),我彈出錯誤消息,按OK,然後繼續添加新的數字,而不會有任何計算錯誤。Java swing異常處理程序

整個程序:

主要

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

只需卸下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) 
    //......... 
    
+0

當我將其刪除時,它幾乎可以工作。但所有計算都在錯誤後停止。 –

+0

@MartynasŽukovas這就是你所期望的。只要你遇到一個錯誤,它應該停止並要求用戶糾正這個問題。然後他們應該再次點擊提交按鈕... – MadProgrammer

+1

@MartynasŽukovas:查看更新 – Azad

2

這裏是一個完全逃脫的對話框彈出窗口的解決方案:使用JFormattedTextField代替JTextField。這會自動處理輸入錯誤。如果輸入了無效值,則默認情況下,無效值將由最後一個有效值替換,但可以使用setFocusLostBehavior進行更改。你可以使用無參數構造函數構造這樣的字段,然後調用setValue(new Integer(0)),然後使用它。如果您需要知道該字段中的數字,則可以使用(Integer) getValue()