0

I want to calculate the value returned on payment of a certain price using keyPressed event on Java .this code :

    private void txtbyrKeyPressed(java.awt.event.KeyEvent evt) {                                  
    int harga = Integer.parseInt(txthrg.getText());
    int byr = Integer.parseInt(txtbyr.getText());
    int kembali = harga-byr;

    txtkmbli.setText(String.valueOf(kembali));

}                                 

i have wrong calculation output and error :

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
  • 3
    You try to convert an empty String into an int => a NumberFormatException is thrown. The error message says it all. – StephaneM May 13 '16 at 12:40

1 Answers1

1

Your getText() methods return empty Strings.

Consider to check your Strings are they numbers before parsing. How to check if a String is numeric in Java

Try this:

private void txtbyrKeyPressed(java.awt.event.KeyEvent evt) {

String hargaString = txthrg.getText();
String byrString = txtbyr.getText();

if( NumberUtils.isNumber( hargaString ) && NumberUtils.isNumber( byrString ) ) {
    int harga = Integer.parseInt(hargaString);
    int byr = Integer.parseInt(byrString);
    int kembali = harga-byr;

    txtkmbli.setText(String.valueOf(kembali));
} }
Community
  • 1
  • 1