簡體   English   中英

NumberFormatException方法

[英]NumberFormatException method

大家好,我想請人幫我。 我想在同一類中編寫一個方法以使用NumberFormatException ,該方法采用JTextField的值並檢查其是否為數字並進行打印。 另外,如何在actionPerformed方法中實現此代碼?

這個主要方法

public class main {
    public static void main(String args[]){
        JavaApplication19 is = new JavaApplication19("title");
        is.setVisible(true);
    }
}

這個GUI類:

public class JavaApplication19 extends JFrame{
    private final JButton button;
    private final JTextField text;
    private final JLabel lable;



    /**
     * @param args the command line arguments
     */ 
    public JavaApplication19(String title){
        setSize(500, 200);
        setTitle(title);
        setDefaultCloseOperation(JavaApplication19.EXIT_ON_CLOSE);

        button = new JButton("enter only number or i will kill you");
        text = new JTextField();
        lable = new JLabel("numbers only");
        JPanel rbPanel = new JPanel(new GridLayout(2,2));
        rbPanel.add(button);
        rbPanel.add(text);
        rbPanel.add(lable);

        Container pane = getContentPane();
        pane.add(rbPanel);

        button.addActionListener(new ButtonWatcher());

        private class ButtonWatcher implements ActionListener{

        public void actionPerformed(ActionEvent a){
            Object buttonPressed=a.getSource();
            if(buttonPressed.equals(button))
            { 

            }
        }
    }
}
if(buttonPressed.equals(button))
{
    try {
        //  try something
    }
    catch (NumberFormatException ex) {
        // do something
    }
}

// try something應該是獲取輸入文本並進行解析的代碼(例如Integer.parseInt(textField.getText()) )。 如果解析由於未輸入數字而不起作用,則將引發NumberFormatException

如果您需要有關如何使用異常的更多信息,請參見異常教程。

編輯:方法

像這樣簡單的事情會起作用

public int parseInput(String input) throws NumberFormatException {
    return Integer.parseInt(input); 
}

或者類似這樣的東西,如果您想捕獲異常

public static int parseInput(String input) {
    int number = 0;
    try {
        number = Integer.parseInt(input); 
    } catch (NumberFormatException ex) {
        someLabel.setText("Must be a number");
        return -1;  // return 0 
    }
}

然后在您執行的動作中,您可以執行以下操作

if(buttonPressed.equals(button))
{
    int n;
    if (parseInput(textField.getText()) != -1){
        n = parseInput(textField.getText());
        // do something with n
    }
}

編輯:布爾方法

public boolean isNumber(String input){
    for (char c : input.toCharArray()){
        if (!Character.isDigit(c))
            return false;
    }
    return true;
}

用法

if(buttonPressed.equals(button))
{
    if (isNumber(textField.getText()){
        // do something
    }
}

編輯:或catch異常

public boolean isNumber(String input){
    try {
        Integer.parseInt(input);
        return true;
    } catch (NumberFormatException ex){
        return false;
    }
}

暫無
暫無

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

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