這是代碼,當我輸入一個字母它不會顯示行.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)
您需要檢查,如果它試圖解析之前匹配。 – shmosel
你需要檢查它是否爲空,然後檢查它是否匹配。 – shmosel
在解析值'if(!receive.matches(「[0-9] +」))''之前檢查此條件。 –