2016-11-12 757 views

回答

0

至少有兩種情況需要關注。

  1. 沒有被輸入
  2. 非數量進入

你也有兩種不同的字段類型

  1. 興趣:十進制類型(如float
  2. 年份:整型(例如。 int

我寫了一些幫助函數來幫助解析「空白」值。這些幫助函數是解決方案,但下面提供了一個可運行的示例。

// Parses a JTextField for a float 
public static float parseFloat(JTextField f, float defaultVal, float failureVal) { 
    if (f == null || f.getText().trim().isEmpty()) { 
     return defaultVal; 
    } else { 
     try { 
      return Float.parseFloat(f.getText()); 
     } catch (NumberFormatException e) { 
      return failureVal; 
     } 
    } 
} 

// Parses a JTextField for an integer 
public static int parseInt(JTextField f, int defaultVal, int failureVal) { 
     if (f == null || f.getText().trim().isEmpty()) { 
      return defaultVal; 
     } else { 
      try { 
       return Integer.parseInt(f.getText()); 
      } catch (NumberFormatException e) { 
       return failureVal; 
      } 
     } 
} 

的功能是不言自明,但目的是爲了讓這兩個「默認」的8.5利息值以及一個誤差值櫃面你想趕上這個問題,並警告用戶。

要使用這些功能,你只需用三個參數調用它們:

System.out.println(parseFloat(rateField, 8.5f, 8.5f)); 
System.out.println(parseFloat(yearField, 1, 1)); 

年輸入處理相同,只是Java中輸入感興趣的處理使用明確的數字類型,所以這是一個副本,粘貼float更改爲int

下面是完整的,工作示例:

import javax.swing.*; 
import java.awt.*; 

public class Main { 
    public static void main(String ... args) { 
     JLabel rateLabel = new JLabel("Rate:"); 
     JTextField rateField = new JTextField(10); 

     JLabel yearLabel = new JLabel("Year:"); 
     JTextField yearField = new JTextField(10); 

     // Use modal to wait for user input for proof of concept 
     JDialog dialog = new JDialog(); 
     dialog.setModal(true); 
     dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
     dialog.setLayout(new FlowLayout()); 
     dialog.getContentPane().add(rateLabel); 
     dialog.getContentPane().add(rateField); 
     dialog.getContentPane().add(yearLabel); 
     dialog.getContentPane().add(yearField); 
     dialog.pack(); 

     dialog.setVisible(true); 

     float rateValue = parseFloat(rateField, 8.5f, 8.5f); 
     int yearValue = parseInt(yearField, 1, 1); 

     JOptionPane.showMessageDialog(null, rateLabel.getText() + rateValue); 
     JOptionPane.showMessageDialog(null, yearLabel.getText() + yearValue); 

    } 

    // Parses a JTextField for a float 
    public static float parseFloat(JTextField f, float defaultVal, float failureVal) { 
     if (f == null || f.getText().trim().isEmpty()) { 
      return defaultVal; 
     } else { 
      try { 
       return Float.parseFloat(f.getText()); 
      } catch (NumberFormatException e) { 
       return failureVal; 
      } 
     } 
    } 

    // Parses a JTextField for an integer 
    public static int parseInt(JTextField f, int defaultVal, int failureVal) { 
      if (f == null || f.getText().trim().isEmpty()) { 
       return defaultVal; 
      } else { 
       try { 
        return Integer.parseInt(f.getText()); 
       } catch (NumberFormatException e) { 
        return failureVal; 
       } 
      } 
    } 
} 
相關問題