Home > other >  Why is parseInt not working for my string?
Why is parseInt not working for my string?

Time:01-01

                String v1=t1.getText();
        int v11 = Integer.parseInt(v1);
        String v3=t3.getText();
        int v33=Integer.parseInt(v3);
                double sum=v11 v33;
                b1.addActionListener(event->{t4.setText(String.valueOf(sum));});

This is a portion of my code where t1 and t3 are textfields.

I am encountering this errorerror

If I enter simple String values in v1 and v3, the code works perfectly and shows result where I want. But since I'm taking user input, I can't go with that. I am not sure why I'm encountering this error. Can someone point out what I'm doing wrong and how to correct it?

ps. I'm a newbie and don't want to add numberformatter, etc. to my code. pls try to keep it simple. thx.

CodePudding user response:

If the input is only numbers then you could add a "0" to the front of the input string to handle for the case shown in the error maybe?

For example: String v = "0" t.getText();

So then the code could be:

String v1="0" t1.getText();
int v11 = Integer.parseInt(v1);
String v3="0" t3.getText();
int v33=Integer.parseInt(v3);
double sum=v11 v33;
b1.addActionListener(event->{t4.setText(String.valueOf(sum));});

CodePudding user response:

There isn't enough context to be 100% sure, but I suspect, based on you comments, the error and the fact that the last thing you do is add an ActionListener to the button, you're trying to read the text fields as part of your initialisation phase of your code, rather then based on some user initiated action.

This would suggest that instead of...

String v1 = t1.getText();
int v11 = Integer.parseInt(v1);
String v3 = t3.getText();
int v33 = Integer.parseInt(v3);
double sum = v11   v33;
b1.addActionListener(event -> {
    t4.setText(String.valueOf(sum));
});

You should actually be doing something more like..

b1.addActionListener(event -> {
    String v1 = t1.getText();
    String v3 = t3.getText();

    if (v1.isBlank() || v3.isBlank()) {
        return;
    }
    try {
        int v11 = Integer.parseInt(v1);
        int v33 = Integer.parseInt(v3);
        double sum = v11   v33;
        t4.setText(String.valueOf(sum));
    } catch (NumberFormatException exp) {
        JOptionPane.showMessageDialog(this, "Invalid input", "Error", JOptionPane.ERROR_MESSAGE);
    }
});

Remember, Swing, like most GUI frameworks is based on a "event" driven workflow, rather then a procedural one.

  • Related