2017-03-03 101 views
1

這是代碼,當我輸入一個字母它不會顯示行.matches相反,我得到一個錯誤,但如果我刪除了parseFloat rec1並刪除其他if( rec1 < total)那麼.matches行會顯示請幫助我如何提前謝謝java.lang.NumberFormatException對於輸入字符串值是字母

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"); 

      } 

//錯誤

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) 
+0

您需要檢查,如果它試圖解析之前匹配。 – shmosel

+0

你需要檢查它是否爲空,然後檢查它是否匹配。 – shmosel

+1

在解析值'if(!receive.matches(「[0-9] +」))''之前檢查此條件。 –

回答

2

從錯誤信息,它看起來就像你正在進入 「asdasd」 到jTextField1。你試圖解析這個值來浮動。如果字符串不是數字,Float.parseFloat(string)將拋出NumberFormatException。在parseFloat()方法中,字符串參數將被轉換爲基本浮點值。

您可以檢查輸入的值是否爲數字,然後將其解析爲浮點數。

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(""); 
     } 

的方法是

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

嘿謝謝你關於這個,它幫助我解決了我的問題,但它運行後有一個小問題,如果我輸入一個字母,它會顯示輸入一個有效金額後,你按OK,然後不足量將彈出如何解決呢?即時通訊抱歉的問題,但即時通訊仍在學習有關Java再次感謝您 – JoMS

+0

嘗試更改後的代碼。這是因爲如果(rec1 <總)檢查保持了 –

+0

@jomsdakis,希望這一次它爲你工作 –

相關問題