Search code examples
javajframejtextfield

java.lang.NumberFormatException For Input String value is letters


This is the Code and when i input a letter it would not display the line .matches instead i got an error but if i remove the parseFloat rec1 and remove the else if (rec1 < total) then the .matches line will display please help me how to do this thank you in advance

CashType c = new CashType(); c.setVisible(true);

    c.jButton1.addActionListener(new java.awt.event.ActionListener() {

        public void actionPerformed(java.awt.event.ActionEvent evt) {
         String receive = c.jTextField1.getText();


         float total = total("sellno"+SellNoCount.getText());
         float rec1 = Float.parseFloat(receive); //this is line 1525

            if(!receive.matches("[0-9]+")){
                JOptionPane.showMessageDialog(null,"Enter a Valid Amount");
                c.jTextField1.setText("");

            }

            else if(receive.equalsIgnoreCase("")){
                JOptionPane.showMessageDialog(null,"Enter Amount");
            }
            else if(rec1 < total){

              JOptionPane.showMessageDialog(null,"Insufficient Amount");

            }

//ERROR

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "asdasd"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.lang.Float.parseFloat(Float.java:451)
at projectfinal.SellPage$32.actionPerformed(SellPage.java:1525)

Solution

  • From the error message, it look like you are entering "asdasd" to jTextField1. This value you are trying to parse to float. Float.parseFloat(string) will throw a NumberFormatException if the String is not a numeric. In parseFloat() method, the string parameter will be converted to a primitive float value.

    You can check the value entered is numeric or not and then parse it to float.

    float rec1 = 0;
    
       if(isNumeric(receive)){
           rec1 = Float.parseFloat(receive);
           if(rec1 < total){
    
             JOptionPane.showMessageDialog(null,"Insufficient Amount");
    
           }
       }else {
              JOptionPane.showMessageDialog(null,"Enter a Valid Amount");
                c.jTextField1.setText("");
             }
    

    The method is

     public static boolean isNumeric(String s) {  
        return s.matches("[-+]?\\d*\\.?\\d+");  
    }