In this code fragment, I can\'t sum a
and b
:
String a = \"10\";
String b = \"20\";
JOptionPane.showMessageDialog(null,a+b);
try: Integer.parseInt(a)+Integer.parseInt(b)
String a= txtnum1.getText();
String b= txtnum2.getText();
JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b));
Since + is used to concat strings, you can't use it to add two strings containing number. But subtraction works perfectly fine with such strings. Hence, you can use this basic mathematical concept to make that possible:
a-(-b)
public void actionPerformed(ActionEvent arg0)
{
String a= txtnum1.getText();
String b= txtnum2.getText();
String result = "";
try{
int value = Integer.parseInt(a)+Integer.parseInt(b);
result = ""+value;
}catch(NumberFormatException ex){
result = "Invalid input";
}
JOptionPane.showMessageDialog(null,result);
}
it is work
Because you want to concat Strings they won't add up. You have to parse them to an Integer which works like:
Integer.parseInt(a) + Integer.parseInt(b)
To sum this up + concats Strings and doesn't add them up.
We can change string to BigInteger and then sum its values.
import java.util.*;
import java.math.*;
class stack
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
String aa=s.next();
String bb=s.next();
BigInteger a=new BigInteger(aa);
BigInteger b=new BigInteger(bb);
System.out.println(a.add(b));
}
}
Java provides parse methods for Primitive Types. So depending on your input you can use Integer.parseInt, Double.parseDouble or others.
String result;
try{
int value = Integer.parseInt(a)+Integer.parseInt(b);
result = String. valueOf(value) ;
}catch(NumberFormatException ex){
//either a or b is not a number
result = "Invalid input";
}
JOptionPane.showMessageDialog(null,result);