Search code examples
javakeylistenernumberformatexception

Number Format Exception in keyListener


weightField.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (!((c >= '0') && (c <= '9') || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) {
              getToolkit().beep();
              e.consume();
            }
            if(serviceTypeComboBox.getSelectedIndex() == 0 && letterTypeComboBox.getSelectedIndex() == 0){
                priceField.setText(Integer.toString((Integer.parseInt(weightField.getText())/500) * 23000));
            }else if(serviceTypeComboBox.getSelectedIndex() == 0 && letterTypeComboBox.getSelectedIndex() == 1){
                priceField.setText(Integer.toString((Integer.parseInt(weightField.getText())/500) * 40000));
            }else if(serviceTypeComboBox.getSelectedIndex() == 1 && letterTypeComboBox.getSelectedIndex() == 0){
                priceField.setText(Integer.toString((Integer.parseInt(weightField.getText())/500) * 11000));
            }else if(serviceTypeComboBox.getSelectedIndex() == 1 && letterTypeComboBox.getSelectedIndex() == 1){
                priceField.setText(Integer.toString((Integer.parseInt(weightField.getText())/500) * 25000));
            }
        }});

I have no idea why I receive java.lang.NumberFormatException when I type a key...: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""


Solution

  • According to your code only:

     weightField.getText()
    

    returning an empty String can trigger the exception. Verify you get a value there. I also recomend you to try/catch for that exception to notify the user that seems to enter a value to a TextField.