WESTKINz
WESTKINz

Reputation: 257

JAVA - how do i keep adding value

I have this button and a text field and i wanted to add value on the variable when the button is clicked everything is working apart from I'm unable to add value to string variable

For example if i put value 20 on tempvalue string it should have 20 and i put 30 it should have 50 but what i get is null2050.
I tried += operator which didn't work.

Isn't there any operator that keep adding value on top it or do i have to write new method ?

private String tempvalue;

btnEnter.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String getTxt = textField.getText();
        tempvalue += getTxt;

        System.out.println(tempvalue);

    }
});

Upvotes: 1

Views: 3071

Answers (3)

e2a
e2a

Reputation: 982

As commented by @Jesper the code are concatenating strings and not applying computations such as sum, subtraction and son on ...

So, try out to change the code to convert from java.lang.String to java.langInteger


Integer tempValue += new Integer( getText );
System.out.println( tempvalue ); 

or using a static method from Integer wrap class

Integer tempValue += Integer.parseInt( getText );
System.out.println( tempvalue );

or then using a int Java type (with auto-box automatically)

int tempValue += Integer.parseInt( getText ).intValue();
System.out.println( tempvalue );

Be careful about string to integer conversions. This can rise a NumberFormatException on runtime.

Upvotes: 1

Loki
Loki

Reputation: 4130

You get Strings from Textfields.

String input = getTxt;

You have to parse the String to an integer or any other number type.

int value = Integer.parseInt(input);

Then you can do calculations.

You should also always check if the User Input really is a number. Use try/catch to avoid wrong input:

int value = 0;
int firstValue = 5; //example variable
try{
    value = Integer.parseInt(input);
}catch(Exception e1){
    System.out.println("Your input could not be parsed to a number");
}
int result = firstValue + value; //always be sure all your values are numbers and not strings
System.out.println("Result: "+result);

In total:

private int tempvalue = 0;

btnEnter.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String getTxt = textField.getText();
        int value = 0;

        try{
            value = Integer.parseInt(getTxt);
        }catch(Exception e1){
            System.out.println("Your input could not be parsed to a number");
        }

        tempvalue += value;

        System.out.println("Result: "+tempvalue);

        }
    });
}

Upvotes: 4

abarisone
abarisone

Reputation: 3783

You're simply concatenating your Strings. In fact you start from null then you add 20 but as a String and then 30 but always as a String. Transform in each step into a number and then you have your result done.

Upvotes: 1

Related Questions