0

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);
        }
    });
}
1
  • Please post your stacktrace of exception Commented Jun 27, 2014 at 11:01

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

Wouldn't it be better to just declare it as String str = "";?
Bad idea. An empty String still fails to parse as an integer and is therefore not a valid "fix" for this issue.
@atc Now Read Answer And Question both Properly.
You're missing the point. The solution isn't to fix the assignment, it's to determine why it isn't being assigned an integer (String) value in the first place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.