简体   繁体   中英

Exception when converting string into integer

I'm a starter in Java. I use Netbeans. Following is a snippet from my code to make a simple calculator to add two numbers. Not including the self generated code for buttons.

Problem

When I try to convert the string str into an integer num1 inside the function plus_buttonActionPerformed and equal_buttonActionPerformed it gives an exception stating:

 exception in thread awt-eventqueue-0 java.lang.numberformatexception for input string  

I made sure that the string is not empty by printing it just above the conversion statement. The code is a bit long. Pardon. What am i doing wrong here.

 public class calc extends javax.swing.JFrame {

/**
 * Creates new form calc
 */
public String str = " "; 
public String action = " ";
public int num1;
public int num2;
public int res;
public calc() {
    initComponents();
}
  private void button3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    str=str.concat("3");

    result.setText(str);

}                                       

private void button6ActionPerformed(java.awt.event.ActionEvent evt) {                                        
 str=str.concat("6"); 
 result.setText(str);

}                                       

private void button9ActionPerformed(java.awt.event.ActionEvent evt) {                                        
 str=str.concat("9");
   result.setText(str);
}                                       

private void resultActionPerformed(java.awt.event.ActionEvent evt) {                                       

   result.setText(str);// 
}                                      

private void button1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
   str=str.concat("1");
   result.setText(str);//
}                                       

private void button2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
     str=str.concat("2");
     result.setText(str);
}                                       

private void button4ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    str=str.concat("4"); // 
    result.setText(str);
}                                       

private void button5ActionPerformed(java.awt.event.ActionEvent evt) {                                        
   str=str.concat("5");  // 
   result.setText(str);
}                                       

private void button7ActionPerformed(java.awt.event.ActionEvent evt) {                                        
 str=str.concat("7");   
 result.setText(str);//
}                                       

private void button8ActionPerformed(java.awt.event.ActionEvent evt) {                                        
 str=str.concat("8");  
 result.setText(str);//
}                                       

private void plus_buttonActionPerformed(java.awt.event.ActionEvent evt) {                                            
   System.out.println(str);
    num1=Integer.parseInt(str);
    System.out.println(num1);
    str=" ";

}                                           

private void equal_buttonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    num2=Integer.parseInt(str);
    res=num1+num2;
    str=""+res;
    result.setText(str);
}                                            


public static void main(String args[]) {


    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(calc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(calc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(calc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(calc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new calc().setVisible(true);
        }
    });
}

As the docs state , a NumberFormatException occurs when:

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

The format of the String you're trying to parse is not a valid integer. Indeed your String's value is a space.

Firstly, you can use trim() to remove whitespace from the edge of the character. Even if you initialise it as an empty String: String str = ""; the NumberFormatException will occur because it is not a valid integer.

So, assign it a non-null, integer value and it'll parse correctly.

Your String str = " "; has space at start and you are concating in it, use trim() or set

String str=""; (Suggested by Rudi and Me too)

 String str=" ";
             ^

To survive from this kind of things you better use trim() to remove leading and trailing Sapces from String .

Morover I suggest you to check the String before parsing like null check and Empty check

if(str ==null || str.trim().equals("")){
//Than don't parse
}

Problem : You can not use concat on null String it should be Empty( atleast ) or set it to "0" or "1" or something integer which is parseable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM